0%

注解反射实现之暴力反射

暴力反射

今天刷视频刷到了手动自定义注解的实现,看到其中有一项可以将private私有属性进行强制反射赋值,于是看完视频后手动实现了一下。代码如下

实现的两个注解
  • MyCompoent(类的注入注解)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.wilburn.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* @author wilburn
* @version 1.0
* @date 2021/6/16 15:05
*/

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyCompoent {

}

  • MyValues(类的属性赋值注解)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.wilburn.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* @author wilburn
* @version 1.0
* @date 2021/6/16 15:06
*/

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

实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.wilburn.entity;

import com.wilburn.annotation.MyCompoent;
import com.wilburn.annotation.MyValues;
import lombok.Data;

/**
* @author wilburn
* @version 1.0
* @date 2021/6/16 15:03
*/

@MyCompoent
@Data
public class People {
@MyValues("1")
private Integer id;
@MyValues("张三")
private String name;
}

测试类实现暴力反射
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.wilburn;

import com.wilburn.annotation.MyCompoent;
import com.wilburn.annotation.MyValues;
import com.wilburn.entity.People;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
* @author wilburn
* @version 1.0
* @date 2021/6/16 15:09
*/

public class test {
public static void main(String[] args) throws Exception {
Class<People> peopleClass = People.class;
MyCompoent myCompoent = peopleClass.getAnnotation(MyCompoent.class);
if(myCompoent!=null){
Constructor<People> constructor = peopleClass.getConstructor(null);
People people = constructor.newInstance();
Field[] declaredField = people.getClass().getDeclaredFields();
for(Field field : declaredField){
MyValues value = field.getAnnotation(MyValues.class);
if(value!=null){
//暴力反射
field.setAccessible(true);

switch (field.getType().getName()){
case "java.lang.Integer" : {
field.set(people,Integer.parseInt(value.value()));;
break;
}
case "java.lang.String" : {
field.set(people,value.value());;
break;
}
//...
}
}
}
System.out.println(people);
}
}
}

总结:private 的属性不能直接进行赋值的说法不是绝对的,field.setAccessible(true);可以通过暴力反射进行赋值。