How can I remove the warning from “id = (PK) m.invoke(obj, (Object []) null);“
private PK getId(T obj) {
PK id = null;
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;
}
I’m assuming PK is a generic type in your class
Due to Java type erasure, the type PK is not available at runtime. But if you accept in your constructor a
Class<PK>instance, then you can get around this by callingklass.cast(...)If for whatever reason you can’t get a reference to the actual runtime type of PK, then you have little recourse but to suppress the warning.