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);
 }
}

posted on 2010-07-11 21:09  sunliho  阅读(130)  评论(0编辑  收藏  举报