1. 程式人生 > >java 反射(四) 反射對屬性、方法的操作

java 反射(四) 反射對屬性、方法的操作

package com.reflect;

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

/**
 * 反射對屬性、方法的操作
 * @author lr
 *
 */

public class Demo4 {

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
		Test test =new Test();
		Class<?> clazz =test.getClass();
		
		Object obj =clazz.newInstance();
		//獲得fun方法 方式一:
		Method method = clazz.getMethod("fun", String.class,int.class);
		//獲得fun方法 方式二:
		Method method2 = clazz.getMethod("fun", new Class[]{String.class,int.class});
		//方法呼叫 方式一:
		method.invoke(obj, "lr",25);
		//方法呼叫 方式二:
		method2.invoke(obj, new Object[]{"lr",25});
		
		//獲取屬性name
		Field fieldName = clazz.getDeclaredField("name");
		Field fieldAge = clazz.getDeclaredField("age");
		
		//私有屬性設定其可獲得
		fieldName.setAccessible(true);
		fieldAge.setAccessible(true);
		//為屬性賦值
		fieldName.set(obj, "tom");
		fieldAge.set(obj, 25);
		//列印屬性值
		System.out.println(fieldName.get(obj));
		System.out.println(fieldAge.get(obj));
		
		
	}
}

class Test{
	private String name;
	
	private int age;
	
	public void fun(String name,int age){
		System.out.println(name+","+age);
	}

	
	public Test() {
		super();
	}


	public Test(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	
}


列印輸出:

lr,25
lr,25
tom
25