forked from faogustavo/JSONApi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Resource.java
96 lines (75 loc) · 2.47 KB
/
Resource.java
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.gustavofao.jsonapi.Models;
import com.gustavofao.jsonapi.Annotations.Excluded;
import com.gustavofao.jsonapi.Annotations.Id;
import com.gustavofao.jsonapi.Annotations.Type;
import com.gustavofao.jsonapi.Annotations.Types;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Resource {
@Id
private String id;
private Links links;
@Excluded
private String type;
@Excluded
protected boolean hasAttributes;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
if (type != null)
return type;
if (getClass().getAnnotation(Type.class) != null)
return getClass().getAnnotation(Type.class).value();
if (type == null && getClass().getAnnotation(Types.class).value() != null && getClass().getAnnotation(Types.class).value().length > 0)
return getClass().getAnnotation(Types.class).value()[0];
return "";
}
public boolean hasAttributes() {
return hasAttributes;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
@Override
public boolean equals(Object o) {
if (o.getClass() != getClass())
return false;
List<Field> fields = getFields(getClass());
for (Field f : fields) {
boolean acessible = f.isAccessible();
try {
f.setAccessible(true);
Object v1 = f.get(this);
Object v2 = f.get(o);
if (v1 == null && v2 == null)
continue;
if ((v1 != null && v2 == null) || (v1 == null && v2 != null))
return false;
if (!f.get(this).equals(f.get(o)))
return false;
} catch (Exception e) {
e.printStackTrace();
}finally {
f.setAccessible(acessible);
}
}
return true;
}
private static List<Field> getFields(Class<?> type) {
List<Field> fields = new ArrayList<>();
fields.addAll(Arrays.asList(type.getDeclaredFields()));
if (type.getSuperclass() != null && !type.getSuperclass().getName().equals(Object.class.getName())) {
fields.addAll(getFields(type.getSuperclass()));
}
return fields;
}
}