反射机制调用无参和有参方法以及调用私有方法

package reflect;

public class Person {
	
	public void sayHello() {
		System.out.println("HelloJava");
	}
	public void sayName() {
		System.out.println("大家好");
	}
	public void sayAge(int age) {
		System.out.println("我的年龄是:"+age+"岁了...");
	}
	public void say(String name,int age) {
		System.out.println("我叫"+name+",我今年"+age+"岁了。");
	}
	private void domose() {
		System.out.println("我是Preson类的私有方法...");
		
	}
}

  

  调用person类中无参方法

package reflect;

import java.lang.reflect.Method;
/**
 * 通过反射机制调用某个类的某个方法
 */

public class ReflectDemo1 {
	public static void main(String[] args) throws Exception  {
		
		Class cls = Class.forName("reflect.Person");
		//接收的是一个Person的实例
		Object o =cls.newInstance();
		/*
		 * 通过该Class实例可以获取其表示的类的相关方法
		 * 获取Person的sayHello方法
		 * 
		 */
		Method method =cls.getDeclaredMethod("sayHello", null);
		method.invoke(o, null);
	}

}

  调用person类中有参方法

package reflect;

import java.lang.reflect.Method;

/**反射调用有参方法
* 
*/
public class ReflectDemo3 {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("reflect.Person");
Object o =cls.newInstance();
Method method=cls.getDeclaredMethod("sayAge",new Class[] {int.class});

method.invoke(o, new Object[] {20});

Method method1=cls.getDeclaredMethod("say",new Class[] {String.class,int.class});
method1.invoke(o,new Object[] {"zhangsan",18});
}

}

  

调用Person类中的私有方法

package reflect;

import java.lang.reflect.Method;

//反射机制调用私有方法
public class ReflectDemo4 {
	public static void main(String[] args) throws Exception  {
		Class cls = Class.forName("reflect.Person");
		Object o =cls.newInstance();
		Method method=cls.getDeclaredMethod("domose",null);
		//强制要求访问该方法  setAccessible(true);
		method.setAccessible(true);
		method.invoke(o, null);
		
	}

}

  

  

原文地址:https://www.cnblogs.com/xyk1987/p/8350528.html