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.

3
  • 2
    possible duplicate of java: how can i do dynamic casting of a variable from one type to another? Commented Dec 25, 2013 at 9: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. Commented Dec 25, 2013 at 9:40
  • ok, thanks, but I browsed through tons of reflecion-related postings and was not able to find a solution to this specific problem.... Commented Dec 25, 2013 at 9:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.