Java中的泛型方法
我不知道如何给它一个更好的标题,因为我真的不知道这种模式在 Java 中被称为什么。
现在我有一个具有此签名的方法:
public Directory getDirectory(Class<? extends Directory> type) { ... }
您可以这样调用它:
MyDirectory directory = (MyDirectory)getDirectory(MyDirectory.class);
对类型的约束确保 MyDirectory
必须从 Directory
派生。
我真正想做的是避免强制转换并减少所需的代码量。在 C# 中,你可能会说:
MyDirectory directory = getDirectory<MyDirectory>();
有没有办法在 Java 中做到这一点或类似的事情?从 1.4 版开始我就没有编写过任何 Java 代码了!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您可以通过将方法本身更改为泛型来避免强制转换:
然后:
这里您使用参数的类型推断来确定
T
的类型。但是您确实必须传递
Class
,否则类型擦除将会启动,并且该方法将不知道创建 :( 的实例的类型有关类型擦除和有关 Java 泛型的所有其他信息,请参阅 Angelika Langer 的 Java 泛型常见问题解答。
Well, you could avoid the cast by changing the method itself to be generic:
and then:
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.