1
2
3
4
5
6
7
8
9
10
11
12
13
|
package
com.annotation.pengbo.annotation;
import
java.lang.annotation.Documented;
import
java.lang.annotation.ElementType;
import
java.lang.annotation.Retention;
import
java.lang.annotation.RetentionPolicy;
import
java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public
@
interface
UserAttribute {
public
String
value()
default
""
;
public
String
name()
default
""
;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
|
package
com.annotation.pengbo.annotation;
import
java.lang.annotation.Documented;
import
java.lang.annotation.ElementType;
import
java.lang.annotation.Retention;
import
java.lang.annotation.RetentionPolicy;
import
java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public
@
interface
UserClass {
public
String
value()
default
""
;
}
|
1
2
3
4
5
6
7
8
9
10
|
package
com.annotation.pengbo.model;
import
com.annotation.pengbo.annotation.UserAttribute;
import
com.annotation.pengbo.annotation.UserClass;
@UserClass(
"user"
)
public
class
User {
@UserAttribute(name=
"uu"
)
private
String
uuid;
@UserAttribute
private
String
name;
//get、set省略...
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public
void
explainAnnotation(T t) throws Exception {
Class<?> entity =t.getClass();
//获取到UserClass的注解
UserClass annotation = entity.getAnnotation(UserClass.
class
);
//输出注解中的value值
System.out.println(annotation.value());
//输出T(实体)类的名字
System.out.println(entity.getName());
for
( Field f : entity.getDeclaredFields() ) {
//设置获得属性的权限
f.setAccessible(
true
);
//获得这个实体中所有的UserAttribute的注解
UserAttribute s =(UserAttribute) f.getDeclaredAnnotations()[
0
];
//输出注解的名字
System.out.println(s.name());
//输出实体的属性名字
System.out.println(f.getName());
//获得实体属性的值
Object
fieldVal = f.
get
(t);
//输出出来
System.out.println(fieldVal);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public
<T> T setAnnotation(Class<?> entity) throws Exception {
// Class<?> entity =t.getClass();
// UserClass annotation = entity.getAnnotation(UserClass.class);
//获得传入的实体类名
String
fieldName = entity.getName();
System.out.println(fieldName);
//实例化它
T t= (T) entity.newInstance();
for
( Field f : entity.getDeclaredFields() ) {
//给它权限(如果不给值能对实体中属性公开的注解操作,例如public)
f.setAccessible(
true
);
//将你想赋的值,设置进去
f.
set
(t,
"hello uuuu"
);
System.out.println(f.getName());
}
//返回它
return
t;
}
|