Question

I don't know how to give this a better title as I don't really know what this pattern is called in Java.

Right now I have a method with this signature:

public Directory getDirectory(Class<? extends Directory> type) { ... }

And you call it like this:

MyDirectory directory = (MyDirectory)getDirectory(MyDirectory.class);

The constraint on the type ensures that MyDirectory must derive from Directory.

What I really want to do is avoid the cast and reduce the amount of code required. In C# you could say:

MyDirectory directory = getDirectory<MyDirectory>();

Is there a way to do this or something similar in Java? I haven't coded any Java since version 1.4!

Was it helpful?

Solution

public <T extends Directory> T getDirectory(Class<T> type) { ... }

MyDirectory directory = getDirectory(MyDirectory.class);

OTHER TIPS

Well, you could avoid the cast by changing the method itself to be generic:

public <T extends Directory> T getDirectory(Class<T> type)

and then:

MyDirectory directory = getDirectory(MyDirectory.class);

Here you're using type inference from the argument to determine the type of T.

But you do have to pass the Class<T> in, as otherwise type erasure will kick in and the method won't know the type to create an instance of :(

For more details of type erasure and just about everything else to do with Java generics, see Angelika Langer's Java Generics FAQ.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top