zoukankan      html  css  js  c++  java
  • 通过反射获取方法返回的类型

    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();
    			}
    		
    	}
    
    }
    
  • 相关阅读:
    Android之Handler实现延迟执行
    static{}语句块
    (转)git常见错误
    smarty使用
    git简易操作
    angular路由——ui.route
    angular服务二
    angular服务一
    angualr 实现tab选项卡功能
    EF 集合版 状态版的 增加、删除、修改 的实践
  • 原文地址:https://www.cnblogs.com/a1111/p/12816436.html
Copyright © 2011-2022 走看看