Created
May 20, 2015 08:49
-
-
Save paven/13e177eae11c5d7706fd to your computer and use it in GitHub Desktop.
reflection to convert from one class to another.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public Dataset toDataset() { | |
Dataset dataset = new Dataset(); | |
for (Method method : Dataset.class.getMethods()) { | |
if (method.getName().startsWith("set")) { | |
Object value; | |
try { | |
String getName = setNameToGetName(method.getName()); | |
value = this.getClass().getMethod(getName).invoke(this, null); | |
} catch (NoSuchMethodException ex) { | |
throw new IllegalStateException("Ett setter hittar ingen getter motsvarighet", ex); | |
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { | |
throw new IllegalStateException("Denna kod ska ej kunan köras.", ex); | |
} | |
try { | |
method.invoke(dataset, value); | |
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { | |
} | |
} | |
} | |
return Dataset; | |
} | |
private String setNameToGetName(String name) { | |
return name.replaceFirst("set", "get"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment