1

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.

AJ.
  • 4,526
  • 5
  • 29
  • 41
matric
  • 27
  • 3
  • 2
    possible duplicate of [java: how can i do dynamic casting of a variable from one type to another?](http://stackoverflow.com/questions/2127318/java-how-can-i-do-dynamic-casting-of-a-variable-from-one-type-to-another) – BobTheBuilder Dec 25 '13 at 09:38
  • The subject you're looking for is called "reflection". There is lots out there on it, and several ReflectionUtils libraries. That's how you call a method or access a property where the name is only known at runtime. – Stewart Dec 25 '13 at 09:40
  • ok, thanks, but I browsed through tons of reflecion-related postings and was not able to find a solution to this specific problem.... – matric Dec 25 '13 at 09:44

1 Answers1

2

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.

erickson
  • 265,237
  • 58
  • 395
  • 493