Skip to content
Advertisement

How to use class type of method parameter?

I have the following classes: Foo1 extends Bar and Foo2 extends Bar

I would like to pass the type of either Foo1, or Foo2 in my method to create either a Foo1, or a Foo2, like this:

public Bar createMethod( "either type of Foo1, or Foo2" fooType) {
    
    //returns the foo1 or foo2
}

Is there any approach to achieve this?

Advertisement

Answer

You can have some flexibility using generics, by declaring:

public <T extends Bar> T createMethod(Class<T> foo) {
    // do the factoring
    retrun (T) foo1 // (or foo2 depending on the foo passed);
} 

With this all the following assignmennts are valid:

Bar b1 = createMethod(Foo1.class);
Bar b2 = createMethod(Foo2.class);
Foo1 f1 = createMethod(Foo1.class);
Foo2 f2 = createMethod(Foo2.class);

Note: at runtime you will get a ClassCastException if you do not return the expected type. So if you fore example do this:

public <T extends Bar> T createMethod(Class<T> foo) {
    return (T)new Foo2();
}

and

Foo1 foo1 = createMethod(Foo1.class);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement