Get specific property of object using java Reflection
I have class User which have different objects like country,address,car and many others. All embedded objects have userid property which is long. I have User object, i want to set userid property of all embedded objects to specific val开发者_如何学编程ue or null using java reflection. Otherwise i have to write methods for each different object.
You can use Apache Common's ReflectionUtils and BeanUtils class to help you out. ReflectionUtils has several helper methods that can help in discovering properties you are interested in and BeanUtils has helper methods to populate the values of properties/fields.
Unless there is a specific reason to use reflection, it is better not to use it.
If you are looking for using reflection because it will be convinient or it will take fewer lines of code/make code readable, then note that this is not true.
Generally reflection code is less readable, and you are almost always better off using the normal way of invoking methods.
Reflection is suitable when, say, your method names are known only at runtime (via a properties file or something)
If for any reason, you need reflection, see this.
If I understood task in correct way, you can do it without reflection.
abstract class Embedded {
private static final Set<Integer> obj = ...;
{
//init obj
}
protected Embedded(int id){
set.add(id);
}
public static Set<Integer> getAllIDs(){
return obj; //return copy or immutable collection
}
}
精彩评论