Welcome to this Blog. I am Software Engineer and work for Zühlke Engineering AG in Bern. This is my private blog, in which I will post mainly about technical stuff like Software Engineering or IT related topics. The views expressed herein do not necessarily represent those of my employer.

 

 
 

 

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
  }
}

 

 

 

 

 
Leave a comment