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

原文地址:https://www.cnblogs.com/mengjianzhou/p/5986856.html