문제

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!

도움이 되었습니까?

해결책

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

MyDirectory directory = getDirectory(MyDirectory.class);

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top