通过反射获取方法返回的类型

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

}
原文地址:https://www.cnblogs.com/a1111/p/12816436.html