Galera, estou apanhando para Generics (Reflection)… Estou tentando fazer duas coisas…
Primeiro: pegar o tipo da classe da chave primária, para depois fazer um casting de String pra ela
Segundo: retornar o valor da chave primaria
Mas o código que eu fiz ta meio suspeito…
Alguém consegue me ajudar
protected Class<?> getPrimaryKeyDeclaringClass(){
Class<?> type = entity.getClass();
for (Field f : type.getDeclaredFields()) {
if (f.getAnnotation(Id.class) != null) {
return f.getDeclaringClass();
}
}
return null;
}
//FIX-ME need to change this :(
@SuppressWarnings("unchecked")
@Override
public T getRowData(String key) {
return getBaseService().findOne( (PK) getPrimaryKeyDeclaringClass().cast(key) );
}
@SuppressWarnings("unchecked")
@Override
public Object getRowKey(T obj) {
PK id = null;
Class<?> type = obj.getClass();
for (Field f : type.getDeclaredFields()) {
if (f.getAnnotation(Id.class) != null) {
String name = f.getName();
String method = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
try {
Method m = type.getDeclaredMethod(method, (Class<?>) null);
id = (PK) m.invoke(obj, (Object []) null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return id;
}

