Reflection
Motivation
@NoArgsConstructor
@Getter
class User {
private String name;
private String email;
}
var user = entitiyManager.find(User.class, 42);
System.out.println(user.getName()); -> "Max"
Wie?
Class
Class<User> clazz = User.class;
clazz = user.getClass();
class Class {
String getName() // -> at.htlstp.domain.User
String getSimpleName() // -> User
Field[] getDeclaredFields()
Constructor[] getDeclaredConstructors()
Method[] getDeclaredMethods()
Field getField(String name)
Constructor getConstructor(Class<?>... parameterTypes)
Method getMethod(String name, Class<?>... parameterTypes)
A getAnnotation(Class<A> annotationClass)
...
getMethods()-> alle public MethodengetDeclaredMethods()-> alle MethodenConstructor,Field,Methodanalog
Annotations
public @interface Entity {
String name default "";
String table();
String[] constraints();
}
@Entity(table = "users", constraints = {"UNIQUE(name)"})
class User {}
Class clazz = User.class
Entity entity = clazz.getAnnotation(Entity.class);
String table = null;
if (entity.table().equals(""))
table = clazz.getSimpleName();
else
table = entity.table();
connection.prepareStatement("create table ? ...")
.setString(1, table);