I have a question regarding reflection in Java.
Following problem:
Depending on a configuration I want to call a method via reflection, but not only of a class CLASS_A, but also from a class CLASS_B that is referenced by CLASS_A.
But I want to use always only class CLASS_A to access the attribute.
Here an example what I mean:
public class Foo
{
private String _name;
private Bar _bar;
public Foo(String name, Bar bar)
{
_name = name;
_bar = bar;
}
public String getName()
{
return _name;
}
public Bar getBar()
{
return _name;
}
}
public class Bar
{
private String _name;
public Bar(String name)
{
_name = name;
}
public String getName()
{
return _name;
}
}
I want to use always an instance of class Foo to invoke the method that is returned by getMethod … no matter whether the method of Foo should be called or the method of Bar.
public class Executor
{
public static void main(String[] args)
{
Foo foo = new Foo("fooName", new Bar("barName"));
String attribute = "barName";
Method method = getMethod(Foo.class, attribute);
try
{
System.out.println(String.valueOf(method.invoke(foo, new Object[]{})));
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
private static Method getMethod(Class< ? > clazz, String attribute)
{
try
{
if (attribute.equals("fooName"))
{
return clazz.getDeclaredMethod("getName", new Class[] {});
}
else if (attribute.equals("barName"))
{
//Is that somehow possible?
Method method = clazz.getDeclaredMethod("getBar.getName", new Class[] {});
return method;
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
}
Is something like that possible?
Thanks!
You can use Apache BeanUtils library.
Here is a good example of how you can use it.