Java 反射机制

Person.java

public class Person {
	private static String TAG = "Person";
	public int id;
	private String name;
	private int age;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

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

	public static String getTAG() {
		return TAG;
	}

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

	public Person() {
		super();
		this.id = 11;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

	public int sum(int... numbers) {
		if (numbers.length == 0)
			return -1;
		int total = 0;
		for (int n : numbers)
			total += n;
		return total;
	}
}

Class类

package reflect;

public class reflectClass {

	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		// 1.通过类来得到Class对象
		Class<?> clz1 = Person.class;
		System.out.println("clz1----->" + clz1);

		// 2.通过对象来获取其Class信息
		Person p = new Person();
		Class<?> clz2 = p.getClass();
		System.out.println("clz2----->" + clz2);

		// 3.通过Class.forName()方式获取Class信息
		Class<?> clz3 = Class.forName("reflect.Person");
		System.out.println("clz3----->" + clz3);

		System.out.println(clz1 == clz2);
		System.out.println(clz3 == clz2);
		
		Class<Person> clz4 = Person.class;
		Person person = clz4.newInstance();
		System.out.println("person----->" + person);
	}

}

输出结果:

clz1----->class reflect.Person
clz2----->class reflect.Person
clz3----->class reflect.Person
true
true
person----->Person [id=11, name=null, age=0]

Field类

package reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class reflectField {

	public static void main(String[] args) throws NoSuchFieldException,
			SecurityException, IllegalArgumentException, IllegalAccessException {
		Person person = new Person(1001, "zhang", 18);
		Class<?> clz = person.getClass();
		// 如何获取公有字段
		Field f = clz.getField("id");
		System.out.println(f);
		Object obj = f.get(person);
		System.out.println("公有字段id----->" + obj);

		// 如何获取私有字段
		f = clz.getDeclaredField("name");
		System.out.println(f);
		f.setAccessible(true);
		obj = f.get(person);
		System.out.println("私有字段name----->" + obj);

		// 如何获取静态字段
		f = clz.getDeclaredField("TAG");
		System.out.println("该属性是否为静态属性:" + Modifier.isStatic(f.getModifiers()));
		System.out.print("获取:");
		f.setAccessible(true);
		System.out.println("" + f.get(null));
		System.out.print("设置 : ");
		f.set(null, "new value");
		System.out.println(Person.getTAG());

		// 获取所有字段
		Field[] fs = clz.getDeclaredFields();
		for (Field field : fs) {
			System.out.println(field);
		}
	}

}

输出结果:

public int reflect.Person.id
公有字段id----->1001
private java.lang.String reflect.Person.name
私有字段name----->zhang
该属性是否为静态属性:true
获取:Person
设置 : new value
private static java.lang.String reflect.Person.TAG
public int reflect.Person.id
private java.lang.String reflect.Person.name
private int reflect.Person.age

Method类

package reflect;

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

public class reflectMethod {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws NoSuchMethodException,
			SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		Person person = new Person(1, "李四", 20);
		Class<Person> clz = (Class<Person>) person.getClass();

		Method method = clz.getMethod("getAge");
		int age = (Integer) method.invoke(person);
		System.out.println(age);

		Method setMethod = clz.getDeclaredMethod("setAge", int.class);
		setMethod.setAccessible(true);
		setMethod.invoke(person, 30);
		System.out.println(person.getAge());

		Method arrayMethod = clz.getDeclaredMethod("sum", int[].class);
		int result = (Integer) arrayMethod
				.invoke(person, new int[] { 1, 2, 3 });
		System.out.println(result);
	}

}

Employee.java

package reflect;

public class Employee {
	private static Employee employee;
	private int id;
	private String name;

	private Employee() {

	}

	private Employee(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public static Employee getInstance() {
		if (employee == null)
			employee = new Employee();
		return employee;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";
	}

}

Constructor类

package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class reflectConstructor {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws InstantiationException,
			IllegalAccessException, NoSuchMethodException, SecurityException,
			IllegalArgumentException, InvocationTargetException {
		// 使用无参/默认构造器创建对象实例
		Class<?> clz = Person.class;
		Person instance = (Person) clz.newInstance();
		System.out.println(instance);

		// 调用公开构造器创建对象实例(有参)
		Constructor<Person> constructors = (Constructor<Person>) clz
				.getConstructor(int.class, String.class, int.class);
		Person person = constructors.newInstance(1001, "李四", 20);
		System.out.println(person);

		Employee employee = Employee.getInstance();
		employee.setId(1001);
		System.out.println(employee);

		Employee employee1 = Employee.getInstance();
		Employee employee2 = Employee.getInstance();

		System.out.println(employee1 == employee2);
		
		Class<Employee> empClz = Employee.class;
		Constructor<Employee> cons = (Constructor<Employee>) empClz.getDeclaredConstructor(int.class,String.class);
		cons.setAccessible(true);
		Employee emp = cons.newInstance(101,"zhang");
		System.out.println(emp);
	}

}

输出结果:

Person [id=11, name=null, age=0]
Person [id=1001, name=李四, age=20]
Employee [id=1001, name=null]
true
Employee [id=101, name=zhang]


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值