1. 程式人生 > >java反射——方法

java反射——方法

反射獲取方法並呼叫。說再多不入程式碼來的快。我把程式碼分成了一塊塊程式碼區,需要看一個註釋其他的就可以了,測試過都是可以的!

package FanShe;

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

class Student3 {
	//**************成員方法***************//
	public void show1(String s){
		System.out.println("呼叫了:公有的,String引數的show1(): s = " + s);
	}
	protected void show2(){
		System.out.println("呼叫了:受保護的,無參的show2()");
	}
	void show3(){
		System.out.println("呼叫了:預設的,無參的show3()");
	}
	private String show4(int age){
		System.out.println("呼叫了,私有的,並且有返回值的,int引數的show4(): age = " + age);
		return "abcd";
	}
}

public class MethodDemo {

	public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		// TODO Auto-generated method stub
		Class c=Student3.class;
		
		/*//父類與自身都獲取public
		Method[] m=c.getMethods();
		for(Method me:m) {
			System.out.println(me);
		}*/
		
		
		 
		
		
		
		//自身全都獲取
				/*Method[] m=c.getDeclaredMethods();
				for(Method me:m) {
					System.out.println(me);
				}*/
				
		
		
		
				
		//獲取自身的指定public方法
			/*	Method m=c.getMethod("show1", String.class);
				
					System.out.println(m);
//			
					Object obj = c.newInstance();
					m.invoke(obj, "傅");*/
				
			
		
		
		
//		//任意方法獲取與呼叫
		Method f=c.getDeclaredMethod("show4", int.class);
		System.out.println(f);
		f.setAccessible(true);
		Object obj=c.newInstance();
		f.invoke(obj, 838768967);
			
				
				
				
	}

}