反射和注解

反射和注解

1.反射

Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法
对于任意一个对象,都能够调用它的任意一个方法和属性
这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制

2.获取字节码的三种方式

2.1通过权限定名 获取字节码对象

Class aClass = Class.forName("com.aaa.day01.test.People");

2.2通过类名获取

Class peopleClass = People.class;

2.3通过对象名获取

People people = new People();
Class aClass1 = people.getClass();

3.通过反射创建对象

反射和注解_第1张图片

Class aClass = Class.forName("com.aaa.day01.test.People");

Constructor constructor = aClass.getConstructor();
Object o = constructor.newInstance(); // People p = new People(); 调用无参构造

Constructor constructor = aClass.getConstructor(int.class);
Object o1 = constructor.newInstance(10); // People p = new People(10); 有参构造

Constructor constructor = aClass.getConstructor(int.class,String.class);
Object o2 = constructor.newInstance(20,"aaa"); // People p = new People(20,"aaa");

//特殊形式 调用无参构造
aClass.newInstance();

4.反射获取方法

反射和注解_第2张图片

Class peopleClass = People.class;

//获取 自己和父类所有的公共函数
Method[] methods = peopleClass.getMethods();

//获取 当前类所有的函数
Method[] declaredMethods = peopleClass.getDeclaredMethods();

4.1字节码对象获取函数信息并且调用

@Test
public void test02(0) throws Exception {

// 1 创建对象
People people = new PeopTe(:
int a = people.eat("胡辣汤):
Class peopleClass = People.class ;
                   
// 自己和父类所有的公共函数
Method[] methods = peop1eCTass .getMethods  ;
 System.out.printIn(Arrays .tostring( methods))!
// 获取当前类所有的函数
Method[] declaredMethods = peop1eClass .getDecTaredMethods ;
System.out.printIn( Arrays .tostring( declaredMethods ));
                   
Method eat = peopleClass .getDeclaredMethod("eat,string.class);
object b = eat.invoke(people,"油馍头");
                                            
Method haha = peopleClass .getDeclaredMethod("haha");
                                            
haha.setAccessible(true);
                                            
haha.invoke(peop1e);
}

4.2字节码获取成员变量并赋值

反射和注解_第3张图片

People people = new People();	

Class peopleClass = People.class;
//获取成员变量
Field[] fields = peopleClass.getDeclaredFields();
//单独拿
Field id = peopleClass.getDeclaredFields("id");
Field name = peopleClass.getDeclaredFields("name");
//打开权限
id.setAccessible(true);
name.setAccessible(true);

id.set(people,666);
id.set(people,"张three");
System.out.println(people);

5.注解

注解就是代码里的特殊标志,可以在编译,类加载运行时被读取,并执行相应的处理

5.1自定义注解


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Role {
    String value();
}

你可能感兴趣的:(Java学习,开发语言,java)