0

I have a set of similar classes that all implement a function of the form

public static ClassA convertToClassA(Obj A)

public static ClassB convertToClassB(Obj B)

I want to loop through a list of classes and call this function that takes one argument of Obj in each class. How do I do this given each function is named differently?

Thanks for the help.

6
  • Can you please explain with code ? Now it's little fishy. Commented Oct 30, 2013 at 8:36
  • 2
    Read little bit more about Java reflection docs.oracle.com/javase/tutorial/reflect Commented Oct 30, 2013 at 8:37
  • Isn't that what an interface would be good for? Commented Oct 30, 2013 at 8:38
  • Can you elaborate? There are more than 20 such classes and I don't intend to change all of them. Commented Oct 30, 2013 at 8:41
  • @user592748. If you have more than 20 classes, how do you know what method to call? How do you know what a specific instance can convert to? Commented Oct 30, 2013 at 8:47

3 Answers 3

3
Class cls = Class.forName("ClassA");
String methodName = "convertTo" + cls.getSimpleName();
Method method = cls.getDeclaredMethod(methodName, new Class[]{Obj.class});
// If the underlying method is static, then the first parameter is ignored. It may be null as illustrated below. 
method.invoke(null, your_object);
Sign up to request clarification or add additional context in comments.

Comments

1

Create common interface with your method signature and let your invokable classes implement it, later on you can iterate over your objects as over instances of interface and call methods from it so no problem. HOWEVER I am starting to think you want to call method without knowing it's name AT ALL - the only knowlage of target method is the number and type of arguments. Well that indeed IS impossible via reflection BUT, it will be innacurate if similar methods signatures will be present. Anyway, don't know what are you trying to do, but your project is badly designed from the ground (no interfaces, poor inharitance I guess etc.)

1 Comment

The interface won't help much if these are static methods.
0

take a look at the reflection package. it provide methods to get back all the methods an instance has provide.

The apache common's BeanUtil (http://commons.apache.org/beanutils) also provide some util method doing similar things.

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.