Skip to content

Instantly share code, notes, and snippets.

@nielsutrecht
Created February 28, 2017 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nielsutrecht/dae858e5bc9fc3f1148ab51c33099ac5 to your computer and use it in GitHub Desktop.
Save nielsutrecht/dae858e5bc9fc3f1148ab51c33099ac5 to your computer and use it in GitHub Desktop.
import java.lang.reflect.Method;
public class ReflectExample {
public static void main(String... argv) throws Exception {
Animal a = new Dog("Max");
for (Method m : a.getClass().getMethods()) {
if (m.getName().startsWith("get") && m.getName().length() > 3 && !m.getName().equals("getClass")) {
String property = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4);
String value = m.invoke(a).toString();
System.out.printf("%s: %s\n", property, value);
}
}
}
public static class Animal {
private int legs;
private String species;
private String subSpecies;
public Animal(int legs, String species, String subSpecies) {
this.legs = legs;
this.species = species;
this.subSpecies = subSpecies;
}
public int getLegs() {
return legs;
}
public String getSpecies() {
return species;
}
public String getSubSpecies() {
return subSpecies;
}
}
public static class Dog extends Animal {
private String name;
public Dog(String name) {
super(4, "Canis. lupus", "Canis lupus familiaris");
this.name = name;
}
public String getName() {
return name;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment