I have a few items from various classes, I would like to write a method taking generic object (Object is the superclass of all other classes)
- verify items all have getId() method
- then collect the getId() value.
Note the object could really by anything - it cannot be bounded
I tried something like
String getObjectId(Object item) throws Exception {
// If the getId() method is not implemented, throw exception
if (Arrays.stream(item.getClass().getMethods())
.filter(method -> "getId".equals(method.getName()))
.findFirst()
.isEmpty()) {
throw new Exception(...);
}
return item.getId();
}
The problem is the compiler ignores this verification - i always get this error even though I just verified it has the method
cannot find symbol
return item.getId();
^
How can I call a method in this case?