@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
public String name() default "mytable";
}
@SuppressWarnings("all")
@DBTable(name="mytable")
public class Person implements Serializable {
@SQLInteger(constraints=@Constraints(primaryKey=true,unique=true))
private int id;
@SQLString(value=12)private String name;
@SQLInteger(value = 5) private int age;
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLInteger {
String name() default "";
int value() default 0;
Constraints constraints() default @Constraints;
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@SuppressWarnings("all")
public @interface SQLString {
String name() default "";
int value() default 0;
Constraints constraints() default @Constraints;
}
@DBTable
@SuppressWarnings("all")
public class Student implements Serializable{
@SQLString(value=12) String name;
@SQLInteger (value = 5) int age;
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Constraints {
boolean primaryKey() default false;
boolean unique() default false;
boolean NULL() default false;
}
@SuppressWarnings("all")
public class AnnotationParse {
public static void main(String[] args) throws ClassNotFoundException {
String colunm = null;
Scanner sc = new Scanner(System.in);
String className = sc.nextLine();
Class<?> cls = Class.forName(className);
DBTable dbtable = cls.getAnnotation(DBTable.class);
if(dbtable!=null){
if(dbtable.name().length()<1){
colunm = cls.getName();
}else{
colunm = dbtable.name();
}
}
//-----------------------------------------------------------------------------------------
ArrayList<String> list = new ArrayList<>();
for(Field f:cls.getDeclaredFields()){
System.out.println(f.getName());
Annotation[] anns = f.getAnnotations();
if(anns[0] instanceof SQLString){
SQLString sqlString = (SQLString)anns[0];
if(sqlString.name().length()<1){
list.add(f.getName()+" VARCHAR("+sqlString.value()+")");
}else{
list.add(sqlString.name()+" VARCHAR(+"+sqlString.value()+")"+getConstraints(sqlString.constraints()));
}
}else if(anns[0] instanceof SQLInteger){
SQLInteger sqlInteger = (SQLInteger) anns[0];
if(sqlInteger.name().length()<1){
list.add(f.getName()+" int("+sqlInteger.value()+")");
}else{
list.add(sqlInteger.name()+" int("+sqlInteger.value()+")"+getConstraints(sqlInteger.constraints()));
}
}
}
//------------------------------------------------------------------------------------------
StringBuffer sqlCommand = new StringBuffer();
sqlCommand.append("Create "+colunm +"{"+"\n");
for(int i = 0;i<list.size()-1;i++){
sqlCommand.append(list.get(i)+","+"\n");
}
sqlCommand.append(list.get(list.size()-1)+"\n"+"}");
System.out.println(sqlCommand);
}
private static String getConstraints(Constraints constraints) {
String str = null;
if(!constraints.NULL()){
str+="NULL";
}else if(!constraints.unique()){
str+="unqiue";
}else if(!constraints.primaryKey()){
str+="primarykey";
}
return str;
}
}