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:

JavaScript

Is there any approach to achieve this?

Advertisement

Answer

You can have some flexibility using generics, by declaring:

JavaScript

With this all the following assignmennts are valid:

JavaScript

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

JavaScript

and

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement