`
grape927
  • 浏览: 73647 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
社区版块
存档分类
最新评论

java 反射

    博客分类:
  • 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 楼 grape927 2012-01-31  
调用Test类中的私有方法getUpdateCount():
Object[] objs = new Object[]{"name", "id"};
Class[] parameterType = new Class[]{Object[].class};
int count = (int)TestUtils.invokMethod(new Test(),
 parameterType, "getUpdateCount", (Object)objs);
assertEquals(count, 1);

相关推荐

Global site tag (gtag.js) - Google Analytics