反射機制調用無參和有參方法以及調用私有方法


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

}

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM