}
package com;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import com.annotation.Column;
import com.annotation.Id;
import com.annotation.Table;
public class BaseDao<T,Pk> {
private Class<T> persistentClass;
@SuppressWarnings("unused")
private Class<Pk> persistentPK;
private String tableName;//表名称
private String id;//主键
public BaseDao() {
ParameterizedType ptype=(ParameterizedType) this.getClass().getGenericSuperclass();
Type[] types = ptype.getActualTypeArguments();
for (Type type : types) {
System.out.println(type.toString());
}
this.persistentPK = (Class<Pk>) types[1];
this.persistentClass = (Class<T>) types[0];
Table table = this.persistentClass.getAnnotation(Table.class);
tableName=table.tableName();
Field[] fields = this.persistentClass.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Id annotationId = field.getAnnotation(Id.class);
if(annotationId != null){
Column annotationCo = field.getAnnotation(Column.class);
id=annotationCo.ColumnName();
break;
}
}
}
public T getT(T t){
System.out.println(tableName);
System.out.println(id);
return t;
}
}
package com;
import com.annotation.Column;
import com.annotation.Id;
import com.annotation.Table;
@Table(tableName = "t_user")
public class User {
@Id
@Column(ColumnName = "uid")
private String id="1";
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public User(String id) {
super();
this.id = id;
System.out.println("有参数");
}
public User() {
System.out.println("没有参数");
}
}
package com;
public class UserDao extends BaseDao<User, String>{
}