java之反射字段,反射方法

反射字段:

package heng.java.reflect.field;

import java.lang.reflect.Field;

public class ReflectFieldDemo {
	public static void main(String[] args) {
		/*
		 * 獲取類中的成員。反射字段。
		 */
		try {
			getFieldDemo();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void getFieldDemo() throws ClassNotFoundException, Exception, Exception{
		String className = "heng.java.reflect.constructor.Person";
		Class clazz = Class.forName(className);
		//
		//Field field = clazz.getField("age");//該方法只獲取公有的。
		Field field = clazz.getDeclaredField("age");
		
		//要對非靜態的字段操作必須有對象
		Object obj = clazz.newInstance();
		//使用父類的方法將訪問權限檢查能力取消。
		field.setAccessible(true);//暴力訪問。
		field.set(obj, 40);
		
		System.out.println(field.get(obj));
	}

}


反射方法:

package heng.java.reflect.method;

import java.lang.reflect.Method;

public class ReflectMethodDemo {
	public static void main(String[] args) {
		try {
			getMethodDemo();
			getMethodDemo2();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//反射方法,靜態,無參數的show方法。
	private static void getMethodDemo2() throws Exception {
		String className = "heng.java.reflect.constructor.Person";
		Class clazz = Class.forName(className);

		Method method = clazz.getMethod("staticShow", null);
		
		method.invoke(null, null);
	}
	//反射方法,非靜態,無參數的show方法。
	public static void getMethodDemo() throws Exception {
		String className = "heng.java.reflect.constructor.Person";
		Class clazz = Class.forName(className);
		
		Method method = clazz.getMethod("show", null);
		Object obj = clazz.newInstance();
		method.invoke(obj, null);
	}
	//反射方法,非靜態,無參數的show方法。
	public static void getMethodDemo3() throws Exception{
		String className = "heng.java.reflect.constructor.Person";
		Class clazz = Class.forName(className);
		
		Method method = clazz.getMethod("paramShow", String.class,int.class);
		Object obj = clazz.newInstance();
		
		method.invoke(obj, "wangwu",22);
		
	}

}


 

Person類:

package heng.java.reflect.constructor;

public class Person {
	private String name;
	private int age;
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Person() {
		super();
		System.out.println("Person run");
	}
	
	public void show(){
		System.out.println("person show run");
	}
	public static void staticShow(){
		System.out.println("person static show run");
	}
	public void paramShow(String name, int age){
		System.out.println("show:"+name+"-----"+age);
	}

}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章