反射实现代码

package com.reflect;

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

public class ReflectTest {

	public static void main(String[] args) throws InstantiationException, IllegalAccessException,
			ClassNotFoundException, SecurityException, NoSuchFieldException {
		// 第一种方式
		Class e1 = Class.forName("com.reflect.Reflect");

		// 第二种方式
		Class r2 = Reflect.class;

		// 第三种方式
		Reflect employee = new Reflect();
		Class r3 = employee.getClass();

		// 获取其类的对象
		Object o = r2.newInstance();

		// 获取所有属性的写法
		Field[] fileds = r2.getDeclaredFields();
		StringBuffer str = new StringBuffer();
		// Modifier是用来获取其修饰符的,getModifiers()方法返回值为int,需要转换通过Modifier类。
		// getSimpleName()是获取其类的简称名字,如果为getName则会获取到com.reflect.name
		str.append(Modifier.toString(r2.getModifiers()) + " class " + r2.getSimpleName() + "{\n");
		for (Field field : fileds) {
			str.append("\t");
			// 获取其属性的修饰符,同样需要通过Modifier类的转换
			str.append(Modifier.toString(field.getModifiers()) + " ");
			// 获取其属性的类型,如果不使用getSimpleName(),则基本类型没问题,但是引用类型则是java.lang.String
			str.append(field.getType().getSimpleName() + " ");
			str.append(field.getName() + ";\n");
		}
		Method[] methods = r2.getMethods();
		for (Method method : methods) {
			str.append("\t");
			// 获取其属性的修饰符,同样需要通过Modifier类的转换
			str.append(Modifier.toString(method.getModifiers()) + " ");
			// 获取其属性的类型,如果不使用getSimpleName(),则基本类型没问题,但是引用类型则是java.lang.String
			str.append(method.getReturnType().getSimpleName() + " ");
			str.append(method.getName() + "();\n");
		}
		str.append("}");
		System.out.println(str);

		// 获取类
		Class e = Reflect.class;
		// 获取其info属性
		Field properties_info = e.getDeclaredField("info");
		// 实例化这个类赋给obj
		Object obj = e.newInstance();
		// 将其private的属性打破,这样可以直接给其属性赋值
		properties_info.setAccessible(true);
		// 给obj对象的info属性赋值"this is information"
		properties_info.set(obj, "this is information");
		System.out.println(properties_info.get(obj));
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值