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

  • 相关阅读:
    739. Daily Temperatures
    556. Next Greater Element III
    1078. Occurrences After Bigram
    1053. Previous Permutation With One Swap
    565. Array Nesting
    1052. Grumpy Bookstore Owner
    1051. Height Checker
    数据库入门及SQL基本语法
    ISCSI的概念
    配置一个IP SAN 存储服务器
  • 原文地址:https://www.cnblogs.com/a1111/p/12816437.html
Copyright © 2011-2022 走看看