I am setting visibility on and off for many elements. Now I want to create a method that will receive an Object
, assuming that every class top parent is Object
, that would be good enough? If that's what I should do, how should I cast them?
And I want to check if the received objects contains a setVisibility
method and if it does perform some actions.
Should I just try and run the method and catch an exception? sounds dumb. What should I do then?
See the first example here, http://java.sun.com/developer/technicalArticles/ALT/Reflection/
import java.lang.reflect.*;
public class DumpMethods {
public static void main(String args[])
{
try {
Class c = Class.forName(args[0]);
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].toString());
}
catch (Throwable e) {
System.err.println(e);
}
}
}
You basically get the class variable for object you are looking at, call the getDeclaredMethods()
to get a array of method names. You can then check to see if the method name exists on the class.
Further down the page there is an example for invoking the method as well.
import java.lang.reflect.*;
public class method2 {
public int add(int a, int b)
{
return a + b;
}
public static void main(String args[])
{
try {
Class cls = Class.forName("method2");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method meth = cls.getMethod(
"add", partypes);
method2 methobj = new method2();
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj
= meth.invoke(methobj, arglist);
Integer retval = (Integer)retobj;
System.out.println(retval.intValue());
}
catch (Throwable e) {
System.err.println(e);
}
}
}