您现在的位置:首页 >> 前端 >> 内容

调用反射类的指定方法

时间:2016/12/19 9:21:02 点击:

  核心提示:package org.entity;import java.lang.reflect.Method;import java.lang.reflect.Type;/*** 本案例演示如何通过反射将字符...
package org.entity;  
  
import java.lang.reflect.Method;  
import java.lang.reflect.Type;  
  
  
/** 
 * 本案例演示如何通过反射将字符串转换为类 
 * */  
public class Test3 {  
    
    public static void main(String[] args) {  
        String user = "org.entity.User";//字符串是该类的全限定名  
            try {  
                Class clzz = Class.forName(user);  
                Object classObj=clzz.newInstance();//将class类转换为对象  
                //--------------------反射类调用User中的sayHello()方法-----------------------------  
                //注意导入正确的Method包名:  
                // import java.lang.reflect.Method;  
                //获取该类的所有方法  
                Method[] methods = clzz.getMethods();  
                //遍历方法  
                for(Method m:methods){  
                    if(m.getName().equals("sayHello2")){//找到sayHello这个方法  
                        //获取返回类型  
                        Type type=m.getGenericReturnType();  
                        //如果返回的是类 (比如user)aa显示为:class org.entity.User  
                        //如果返回的是普通数据类型(int) aa显示为:int  
                        String aa=type.toString();  
                        String nameString="";  
                    }  
                }  
            } catch (ClassNotFoundException e) {  
                e.printStackTrace();  
            } catch (InstantiationException e) {  
                e.printStackTrace();  
            } catch (IllegalAccessException e) {  
                e.printStackTrace();  
            }  
          
    }  
  
}

作者:网络 来源:1111的博客