reflection example
package jdbc.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionQuery {
public static void main(String[] args) throws SecurityException,
IllegalArgumentException, NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException {
User user = create(User.class);
invokeMethod(user,"toString",null,null);
}
private static<T> T create(Class<T> cls) throws SecurityException,
NoSuchMethodException, IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException{
Constructor<T> cst = cls.getConstructor(null);
return cst.newInstance(null);
}
private static<T> void invokeMethod(T ins,String methodName,Object[] paras ,
Class ...paraClass) throws SecurityException,
NoSuchMethodException,IllegalArgumentException, IllegalAccessException,
InvocationTargetException{
Class cls = ins.getClass();
Method mtd = cls.getDeclaredMethod(methodName, paraClass);
if (mtd != null)
mtd.invoke(ins, paras);
}
}
浙公网安备 33010602011771号