Created
February 28, 2017 13:36
-
-
Save nielsutrecht/dae858e5bc9fc3f1148ab51c33099ac5 to your computer and use it in GitHub Desktop.
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
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