grape927 发表于 2013-2-3 13:08:26

java 反射

在运行时从某些外部源读取类名反射不适合
 
private Object reflectClassByInstance(Object instance,               String methodName, Object[] parameterObjects) {         try {               Class c = Class.forName("java.util.logging.LogManager");               Constructor constructor = c.getDeclaredConstructor(null);               constructor.setAccessible(true); // 设置可以访问.               instance = constructor.newInstance();               Method[] m1 = c.getDeclaredMethods();               for (Method method : m1) {                   if (method.getName().equals(methodName)) {                         method.setAccessible(true);                         return method.invoke(instance, parameterObjects);                   }               }         } catch (Exception ex) {               ex.printStackTrace();         }             return null;       }     
Constructor getConstructor(Class[] params) //获得使用特殊的参数类型的公共构造函数,      Constructor[] getConstructors() // 获得类的所有公共构造函数      Constructor getDeclaredConstructor(Class[] params) //获得使用特定参数类型的构造函数(与接入级别无关)      Constructor[] getDeclaredConstructors() //获得类的所有构造函数(与接入级别无关)    
Method getMethod(String name, Class[] params) //使用特定的参数类型,获得命名的公共方法      Method[] getMethods() //获得类的所有公共方法      Method getDeclaredMethod(String name, Class[] params) //使用特写的参数类型,获得类声明的命名的方法      Method[] getDeclaredMethods() //获得类声明的所有方法     
Field getField(String name) //获得命名的公共字段      Field[] getFields() //获得类的所有公共字段      Field getDeclaredField(String name)//获得类声明的命名的字段      Field[] getDeclaredFields() //获得类声明的所有字段 
 
java.lang.IllegalArgumentException: wrong number of arguments
 
Object[] objs= new Object[]{"t1","t2"};
Class[] parameterType = new Class[]{Object[].class};
String str = (String)invokMethod(parameterType, "comp", (Object[])objs);
 
(Object[])objs 会当做参数个传入,应该改为 (Object)objs
 
 
页: [1]
查看完整版本: java 反射