1

I want to pass a Class as parameter and return an instance of this class. I need ensure that the class implements ISomeInterface. I know I can do it with reflection:

Object get(Class theClass) {
    return theClass.newInstance();
}

What I do not know is how to ensure that theClass implements ISomeInterface

ISomeInterface get(Class<? extends ISomeInterface> theClass) {...}
// errrr... you know what i mean?

I don't like reflection in production, but is it very handful for testing

Related:

Community
  • 1
  • 1
Jakub M.
  • 32,471
  • 48
  • 110
  • 179

4 Answers4

2

Use isAssignableFrom.

ISomeInterface get(Class<? extends ISomeInterface> theClass) {
    if (ISomeInterface.class.isAssignableFrom(theClass)) {
        return theClass.newInstance();
    } else { /* throw exception or whatever */ }
}
sebastian_oe
  • 7,186
  • 2
  • 18
  • 20
1

Take a look here Class.isAssignableFrom(java.lang.Class c)

Admit
  • 4,897
  • 4
  • 18
  • 26
1

You have to explicitly check whether the given class object is not of an interface. isAssignableFrom() will return true even if you have both the class objects of interfaces.Since they are on the same hierarchy, it will return true.

I suggest you to try the following code

ISomeInterface get(Class<? extends ISomeInterface> theClass) {
if(!clazz.isInterface()){
    if (ISomeInterface.class.isAssignableFrom(theClass)) {
        return theClass.newInstance();
    } else { /* throw exception or whatever */ }
}
}
shikjohari
  • 2,278
  • 11
  • 23
0

You can use generics:

public <T extends ISomeInterface> T get(Class<T> theClass) {
   return theClass.newInstance();
}
mabg
  • 1,894
  • 21
  • 28