zoukankan      html  css  js  c++  java
  • java 反射类Method的使用

    package com.robert.reflect;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class InvokerTest 
    {
    	
    	public int add(int a, int b)
    	{
    		return a + b;
    	}
    	
    	public String echo(String str)
    	{
    		return "echo " + str;
    	}
    	
    	public static void main(String[] args)
    	{
    		Class classType = InvokerTest.class;
    		try {
    //			Object invokerTest = classType.newInstance();        //构造默认构造器
    			Object invokerTest = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
    			
    			Method addMethod = classType.getMethod("add", new Class[]{int.class,int.class});
    			Object result = addMethod.invoke(invokerTest, new Object[]{100,200});
    			System.out.println(result.toString());
    			
    			Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
    			Object echoResult = echoMethod.invoke(invokerTest, new Object[]{"hello world"});
    			System.out.println(echoResult.toString());
    			
    		} catch (InstantiationException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			e.printStackTrace();
    		} catch (NoSuchMethodException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (InvocationTargetException e) {
    			e.printStackTrace();
    		}
    	}
    }
    

  • 相关阅读:
    OpenCV 之 图像平滑
    C++11 之 nullptr
    C++11 之 scoped enum
    C++ 之 常量成员函数
    德国的挑战
    OpenCV 之 直方图处理
    OpenCV 之 霍夫变换
    排序算法之——归并排序(两种方法及其优化)
    排序算法之——快速排序(剖析)
    排序算法之——桶排序
  • 原文地址:https://www.cnblogs.com/mengjianzhou/p/5986856.html
Copyright © 2011-2022 走看看