0
Files
reflection-object/src/main/java/ru/dmitriymx/reflection/ReflectionField.java

88 lines
2.2 KiB
Java

package ru.dmitriymx.reflection;
import lombok.EqualsAndHashCode;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
@EqualsAndHashCode
public class ReflectionField {
private final Object object;
private final Class clazz;
private final Field field;
public ReflectionField(Object object, Field field) {
this.object = object;
this.clazz = object.getClass();
this.field = field;
}
public ReflectionField(Class clazz, Field field) {
this.object = null;
this.clazz = clazz;
this.field = field;
}
public String name() {
return field.getName();
}
public Class<?> type() {
return field.getType();
}
public ReflectionObject get() {
try {
if (!field.isAccessible()) {
field.setAccessible(true);
}
return new ReflectionObject(field.get(object));
} catch (IllegalAccessException e) {
throw new ReflectionException(e);
}
}
public <T> T get(Class<T> clazz) {
return get().getOriginalObject(clazz);
}
public ReflectionMethod getter() {
final String methodName = "get" + formatNameForMethod();
ReflectionMethod method = new ReflectionObject(object).method(methodName);
if (method.returnType().equals(type())) {
return method;
} else {
return null;
}
}
public ReflectionMethod setter() {
final String methodName = "set" + formatNameForMethod();
return new ReflectionObject(object).method(methodName, type());
}
public boolean isStatic() {
return Modifier.isStatic(field.getModifiers());
}
public <T extends Annotation> T annotation(Class<T> annotationType) {
return field.getAnnotation(annotationType);
}
@Override
public String toString() {
return "ReflectionField{" +
"objectClass=" + clazz +
", fieldName=" + field.getName() +
", isStatic=" + isStatic() +
'}';
}
private String formatNameForMethod() {
return name().substring(0, 1).toUpperCase() + name().substring(1);
}
}