Java反射

反射的简单操作

通过反射创建构造器、调用对象的属性、调用对象的方法

package com.imu.pojo.Person

// 创建Person类
public class Person {
    private String name;
    public int 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;
    }

    public Person() {
    }

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

    private Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public void show(){
        System.out.println("你好,我是🔔");
    }

    private String showNation(String nation){
        System.out.println("喷子实在太多了!!!" + nation);
        return nation;
    }
}

调用公有构造器、属性、方法

// 调用公有结构
// 通过反射创建对象
Class personClass = Person.class;
Constructor c = personClass.getConstructor(String.class, int.class);
Person person = (Person) c.newInstance("张三", 20);

// 通过反射调用属性
Filed name = personClass.getDeclaredFiled("age");
name.set(person, 10);
 
// 通过反射调用方法
Method show = personClass.getDeclardeMethod("show");
method.invoke(person, "China");

调用私有构造器、属性、方法

// 调用私有结构
// 创建对象
Class personClass = Person.class;
Constructor c = personClass.getDeclareConstructor(String.class);
c.setAccessible(true);
Person person = (Person) c.newInstance("张三");

// 调用私有属性
Filed filed = personClass.getDeclareFiled("name");
filed.setAccessible(true);
filed.set(person, "李四");

// 调用私有方法
Method method = personClass.getDeclare("showNation", String.class);
method.setAccessible(true);
String nation = (String) method.invoke(person, "China");

获取Class实例的四种方式

// 无论以哪种方式进行获取,得到的都是同一个运行时类
// 加载到内存的运行时类,会缓存一定的时间。在该时间内,我们可以通过不同的方式来获取此运行时类。

// 1: 调用运行时类的属性
Class clazz = Person.class;

// 2: 通过运行时类的对象获取
Person p = new Person();
Class clazz = p.getClass();

// 使用频率最高]
// 3: 调用Class的静态方法 forName(String classPath)
Class clazz = Class.forName("com.imu.pojo.Person");

// 4(了解): 使用类加载器
ClassLoader classLoader = 当前类.class.ClassLoader();
Class clazz = classLoader.loadClass("com.imu.pojo.Person");

通过ClassLoader加载配置文件

// 获取当前类的ClassLoader
ClassLoader classLoader = 当前类.class.getClassLoader();

// classpath: 配置文件的路径,路径默认为src
InputStream in = classLoader.getResoucesAsStream("classpath");
Propreties pro = new Properties();
pro.load(in);
String user = pro.getProperty("user");

创建运行时类的对象(newInstance)

使用newInstance,应该注意一下几个问题:

  1. 运行时类必须提供空参构造器,否则抛出InstantiationException
  2. 空参构造器不能是private权限,否则抛出IllegalAccessException
// 通过反射创建对应的运行时类的对象
Class clazz = Class.forName("com.imu.pojo.Person");
Object obj = clazz.newInstance(); // 内部调用类的空参构构造器
Person person = (Person) obj;

获取运行时类的属性及其内部结构

获取属性结构

Class personClass = Person.class;

// getFileds(): 获取当前运行时类及其父类中声明为public访问权限的属性
Filed[] fileds = personClass.getFileds();

// getDeclareFileds(): 获取当前运行时类自己声明的任何权限的属性(不包含父类声明的属性)
Filed[] fileds = personClass.getDeclaredFileds();

/** getModifiers(): 获取权限修饰符,返回为int
	public : 1
	default: 0
	private: 2
	Modifier.toString(int modifier): 将int转为具体的权限
	
	getType(): 获取数据类型
	
	getName(): 获取属性名
**/
for (Filed filed : fileds) {
    int modifier = f.getModifiers();
    Modifer.toString(modifier);
    
    Class type = f.getType().getName();
    
    String name = f.getName();
}

获取方法结构

@xxx
权限修饰符 返回值类型 方法名 (参数类型1 形参1, 参数类型2 形参 2.....) throws xxxException{}

Class personClass = Person.class;

// getMethods(): 获取当前运行时类及其父类中声明为public访问权限的方法
Method[] methods = personClass.getMethods();

// getDeclareFileds(): 获取当前运行时类自己声明的任何权限的方法(不包含父类声明的方法)
Method[] methods = personClass.getDeclaredMethods();

// 获取方法声明的注解
for (Method method : methods) {
    // getAnnotations(): 获取方法声明的所有注解
    Annotation[] annos = method.getAnnotations();
    for (Annotation anno : annos) {
 		Sout(anno);       
    }
    
    // getModifiers(): 获取权限修饰符
    String modifier = Modifier.toString(method.getModifiers());
   
    // getReturnType(): 获取返回值类型
    String returnName = mothod.getReturnType().getName();
    
    // getName(): 获取方法名
    method.getName():
    
    // getParameterTpyes(): 获取形参列表	
    Class[] parms = method.getParameterTypes();
	    
   	// getExceptionTypes(): 获取异常
    Class[] exceptions = method.getExceptionTypes();
}

获取构造器结构

Class personClass = Person.class;

// getConstructors(): 获取当前运行时类中声明为public的构造器
Constructor[] c = personClass.getConstructors();

// getDeclredConstructors(): 获取当前运行时类中声明的所有的构造器
Constructor[] c = personClass.getDeclredConstructors();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值