Bläddra i källkod

Ajout méthode utilitaire annotation

Arthur Brandao 5 år sedan
förälder
incheckning
bbf190d155
1 ändrade filer med 61 tillägg och 6 borttagningar
  1. 61 6
      src/db/DatabaseUtils.java

+ 61 - 6
src/db/DatabaseUtils.java

@@ -1,23 +1,50 @@
 package db;
 
+import java.lang.annotation.Annotation;
 import java.lang.reflect.Field;
 
+import db.annotation.DbField;
+import db.annotation.DbId;
 import db.annotation.DbLink;
 
 public class DatabaseUtils {
 	
-	public static void checkIfPersistable(Field f) {
-		boolean ok = false;
-		for(Class<?> clazz : f.getType().getInterfaces()) {
-			ok |= clazz.getName().endsWith("Persistable");
+	public static boolean isPersistable(Class<?> clazz) {
+		for(Class<?> interfaces : clazz.getInterfaces()) {
+			if (interfaces.getName().endsWith("Persistable")) {
+				return true;
+			}
 		}
-		if (!ok) {
+		return false;
+	}
+	
+	public static void checkIfPersistable(Field f) {
+		if (!isPersistable(f.getType())) {
 			throw new IllegalStateException("Field object don't implement Persistable");
 		}
 	}
 	
+	public static boolean isDbId(Field f) {
+		return isAnnotation(f, DbId.class);
+	}
+	
+	public static boolean isDbField(Field f) {
+		return isAnnotation(f, DbField.class);
+	}
+	
+	public static String getDbField(Field f) {
+		if (!isDbField(f)) {
+			return null;
+		}
+		return f.getAnnotation(DbField.class).value();
+	}
+	
+	public static boolean isDbLink(Field f) {
+		return isAnnotation(f, DbLink.class);
+	}
+	
 	public static String getDbLink(Field f) {
-		if (!f.isAnnotationPresent(DbLink.class)) {
+		if (!isDbLink(f)) {
 			return null;
 		}
 		String val = f.getAnnotation(DbLink.class).value();
@@ -26,5 +53,33 @@ public class DatabaseUtils {
 		}
 		return val;
 	}
+	
+	public static Field getIdField(Class<?> clazz) {
+		if (!isPersistable(clazz)) {
+			return null;
+		}
+		for(Field f : clazz.getFields()) {
+			if (isDbField(f) && isDbId(f)) {
+				return f;
+			}
+		}
+		return null;
+	}
+	
+	public static <T extends Persistable> Persistable getDbLinkObject(Field f, T obj) {
+		if (!isDbLink(f)) {
+			return null;
+		}
+		checkIfPersistable(f);
+		try {
+			return (Persistable) f.get(obj);
+		} catch (IllegalArgumentException | IllegalAccessException e) {
+			return null;
+		}
+	}
+	
+	private static boolean isAnnotation(Field f, Class<? extends Annotation> clazz) {
+		return f.isAnnotationPresent(clazz);
+	}
 
 }