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显示为:intString aa=type.toString();String nameString="";}}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}}