java编程 反射类的使用

使用反射类调用该类方法:

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

注明:该代码转自浪曦视频。仅供学习和参考。如有问题,本人qq362601125


posted @ 2012-03-28 07:15  梦见舟  阅读(136)  评论(0编辑  收藏  举报