java反射调用方法

1:Class类中的方法

public Method getDeclaredMethod(String name,
                                Class<?>... parameterTypes)
                         throws NoSuchMethodException,
                                SecurityException
參数:
name - 方法名
parameterTypes - 參数数组
返回:
该类与指定名和參数相匹配的方法的 Method 对象 

2:Method类中的方法;

public Object invoke(Object obj,
                     Object... args)
              throws IllegalAccessException,
                     IllegalArgumentException,
                     InvocationTargetException
參数:
obj - 从中调用底层方法的对象
args - 用于方法调用的參数
返回:
使用參数 argsobj 上指派该对象所表示方法的结果 3:hello world!级别的反射调用:

package com.dao.Text;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TetsReflect {

	/**
	 * @param args
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public static void main(String[] args) throws SecurityException,
			NoSuchMethodException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		Person p = new Person();
		Class cla = p.getClass();
		// 1:无參数
		Method method1 = cla.getDeclaredMethod("print");
		method1.invoke(p);
		// 2:有參数的调用
		Method method2 = cla.getDeclaredMethod("printParameter", String.class);
		method2.invoke(p, "hello world!!");
	}
}

class Person {
	public void print() {
		System.out.println("hello world!!"+"没有參数反射方法的调用");
	}

	public void printParameter(String param) {
		System.out.println(param+"有參数的反射方法的调用");
	}
}

结果:

hello world!!没有參数反射方法的调用
hello world!!有參数的反射方法的调用

posted @ 2017-07-01 16:51  brucemengbm  阅读(522)  评论(0编辑  收藏  举报