推荐于2016-06-08 08:21:31
最佳答案
自定义注解,可以应用到反射中,比如自己写个小框架。
如实现实体类某些属性不自动赋值,或者验证某个对象属性完整性等
本人自己用过的验证属性值完整性:
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
48
49
50
51
52
53
54
|
@Target
(ElementType.FIELD)
@Retention
(RetentionPolicy.RUNTIME)
public
@interface
IgnoreProperty {
}
然后实体类中:
public
class
TarResearch
implements
Serializable{
@IgnoreProperty
private
static
final
long
serialVersionUID = 1L;
@IgnoreProperty
private
Integer researchId;
@IgnoreProperty
private
TarUser userId;
private
String version;
private
String grade;
....
}
然后action类中
// 验证数据完整性
Class<TarResearch > userClass = TarResearch .
class
;
Field[] field = userClass.getDeclaredFields();
for
(
int
i =
0
; i < field.length; i++) {
if
(field[i].getAnnotation(IgnoreProperty.
class
) !=
null
) {
continue
;
}
String fie = field[i].getName().substring(
0
,
1
).toUpperCase()
+ field[i].getName().substring(
1
);
Method method = userClass.getMethod(
"get"
+ fie);
Object obj = method.invoke(u);
if
(obj ==
null
) {
sendResponseMsg(response,
"数据错误"
);
return
null
;
}
}
|