Reputation: 27
I have a Java method which accept as arguments a List
of objects, a String
specifying the class name of those objects, and a String
specifying a property of those objects:
public void myMethod (List list, String className, String property) {
for (int n=0;n<list.size();n++) {
x = list.get(n);
System.out.println(x.property);
}
}
The method must be applied to lists containing possibile different object types.
Of course the method above does not work because the objects retrieved from the list need to be (dynamically) casted, but I have not been able to figure out how to do it.
For instance, the following does not work:
Class.forName(className) x = (Class.forName(className)) list.get(n);
I guess the problem is trivial, but how should I solve it?
Thank you.
Upvotes: 1
Views: 286
Reputation: 269657
Casting is useful when the target types are known at compile-time. It sounds like you want this to work for any type available at runtime, so it's a better fit for reflection.
public void myMethod (List list, String className, String property)
throws Exception
{
Class<?> clz = Class.forName(className);
Method mth = clz.getMethod(property);
for (Object el : list) {
Object r = mth.invoke(el);
System.out.println(r);
}
}
Java 8 makes this sort of thing much easier.
Upvotes: 2