这个Java 提供的注解,以下是我写的一个通过数据库查询的SQL的列到JavaEntity的映射,使用的是Hibernate 的注解,仅供参考。
public static Object getClass(String[] column, Class> clazz, Object obj) {
if (column == null || column.length == 0 || clazz == null || obj == null)
return null;
Field[] fields = clazz.getDeclaredFields();
Object[] objs = (Object[]) obj;
try {
Object bean = clazz.newInstance();
for (int x = 0; x < column.length; x++) {
for (int i = 0; i < fields.length; i++) {
if (!fields[i].isAccessible()) {
fields[i].setAccessible(true);
}
Column annoColumn = fields[i].getAnnotation(Column.class);
if (annoColumn != null && annoColumn.name().equals(column[x])) {
Object valueObject = objs[x];
String value = null;
if (valueObject != null) {
value = valueObject.toString();
}
if (value != null) {
if (fields[i].getType().getSimpleName().equalsIgnoreCase("long")) {
fields[i].set(bean, Long.valueOf(value));
} else if (fields[i].getType().getSimpleName().toLowerCase().indexOf("int") != -1) {
fields[i].set(bean, Integer.valueOf(value));
} else if (fields[i].getType().getSimpleName().equalsIgnoreCase("short")) {
fields[i].set(bean, Short.valueOf(value));
} else if (fields[i].getType().getSimpleName().equalsIgnoreCase("double")) {
fields[i].set(bean, Double.valueOf(value));
} else if (fields[i].getType().getSimpleName().equalsIgnoreCase("float")) {
fields[i].set(bean, Float.valueOf(value));
} else if (fields[i].getType().getSimpleName().toLowerCase().indexOf("char") != -1) {
if (value.length() > 0) {
fields[i].set(bean, Character.valueOf(value.toCharArray()[0]));
}
} else if (fields[i].getType().getSimpleName().equalsIgnoreCase("byte")) {
fields[i].set(bean, Byte.valueOf(value));
} else if (fields[i].getType().getSimpleName().equals("String")) {
fields[i].set(bean, String.valueOf(value));
}
}
}
}
}
return bean;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
这是导入了javax包中的包annotation包中的类Resource