Search code examples
javaclassgenericstype-safety

How to require .class parameter to be a certain class in Java?


For example, I want to do something like:

public void foo(Class c){
    doSomething();
}

But I want the Class c parameter to be a class that has implemented a specific interface. Is there a way to enforce this at compile time?


Solution

  • You can use generics:

    public void foo(Class<? extends SomeInterface> c){
        doSomething();
    }