问题
i will discribe my problem with the following example:
public class Person{
private int age;
private String name;
public Person(int age, String name){
this.age = age;
this.name = name;
}
}
I ve a class with some Members (age and name in this case) but i don't know which and how much my class does have. Also i don't even care about the amount or the types. I wan't to get all members of only one class. like this:
private List<Object> getAll(Class searchedClass, Object from){
// This is where the magic happens
}
This method shall return a List with every not null object which is an instance of the Class "searchedClass" and is a member of the Object "from".
In my case i've classes called Property and PropertyContainerList and an interface called PropertyContainer. A PropertyContainerList can only contain objects which implements my interface PropertyContainer. So a class could've 10 Properties as members and another one cuold've 5 but objects of both can be added. A Property has the method addListener(...). I want, every time an object is added to my list, to add an listener to every "Property"-member of the object. so like this:
if(instance of PropertyContainer is added){
List<Property> properties = getAll(Property.class, propertyContainerObject);
for(Property property : properties)
property.addListener(new Listener());
}
I tried a few things but i've no idea how to realize the getAll(Class, Object) method. Please help :)
Thanks for answers
回答1:
What you probably need is reflection. Read the reflection trail in the Java tutorial.
Reflection allows you to inspect at runtime what member variables and functions a class has, and to read from and write to the member variables.
回答2:
Field f = Class.getDeclaredField("fieldname");
Object o = f.get(ObjectToGetMemberFrom);
This did it for me :)
回答3:
I recomend you have a look at this post:
Java - Get a list of all Classes loaded in the JVM
on how to load all classes in a certain package or the entire JVM. Once a List of all loaded/ known classes is available you will have to:
1.) Check per class in the list if it is implementing the desired Interface
2.) If so use Reflection methods to read desired "members" (fields and/or methods) according to http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html
Also note that with reflection (it worked with JDK 1.4 lol...) you are possibly still able to change private to public at runtime to read all of those fields as well.
NOTE: To get a list of "all" classes i will rely on this google library rather than doing it all from scratch: http://code.google.com/p/reflections/downloads/detail?name=reflections-0.9.9-RC1-uberjar.jar&can=2&q=
来源:https://stackoverflow.com/questions/26420934/get-member-fields-of-an-existing-object