Skip to content

Instantly share code, notes, and snippets.

@paven
Created May 20, 2015 08:49
Show Gist options
  • Save paven/13e177eae11c5d7706fd to your computer and use it in GitHub Desktop.
Save paven/13e177eae11c5d7706fd to your computer and use it in GitHub Desktop.
reflection to convert from one class to another.
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