Welcome to the Joint-Venture Blog from Fabio Cortesi and Stefan Jäger.
27.06.2008 - Stefan Jäger
Generics are very useful. But sometimes, they don’t fullfil all required needs. Today, I had a small problem. Over the parameter of a method, a Class definition was passed. In the method, I had to cast an object of type Object into a concrete type (the concrete type was T, defined by Generics). The easiest way is to put the cast between a try and catch block. This will work, no question. But in my piece of code, a try and catch block wasn’t very nice. For this reason, I tried to check, if the object o is of the type clazz. Unfortunately, instanceof doesn’t work with dynamic defined classes. But there is a simple solution: just use the method isAssignableFrom.
private void test(Class<?> clazz) { // the Object o is from somewhere... if (o instanceof clazz) { // does not working } if (o.getClass().isAssignableFrom(clazz)) { // is working } }
Comments
Leave a comment