Java反射一 动态修改类的属性

Person.java

package fanshe;

public class Person {
	private int age;
	private String name;
	
	private String info(){
		return "My name is "+ name +", I'm "+age+" years old.";
	}
	
	private void sayHellow(String word){
		System.out.println(word);
	}
}


Mymain.java

package fanshe;

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

public class Mymain {
	
	public static void main(String[] args) throws Exception{
		Mymain.ceratePerson("fanshe.Person", "name", "Peter", "age", 30, "info");
	}
		
	private static void ceratePerson(String className, String namefield, String namevalue,  String agefield, int agevalue, String methodname) throws Exception{
		Class clazz = Class.forName(className);
		Object o = clazz.newInstance();
		
		Field field_name = clazz.getDeclaredField(namefield);
		field_name.setAccessible(true);
		field_name.set(o, namevalue);
		
		Field field_age = clazz.getDeclaredField(agefield);
		field_age.setAccessible(true);
		field_age.setInt(o, agevalue);
		
		Method method = clazz.getDeclaredMethod(methodname);
		method.setAccessible(true);
		String result =  (String)method.invoke(o);
		System.out.println(result);
	}
}


运行结果:
My name is Peter, I'm 30 years old.

你可能感兴趣的:(java反射)