“使用” Java 中的指令
当类型名称太长时,在 C# 中我可以像这样创建别名:
using Dict = System.Collections.Generic.Dictionary<string, string>;
我可以像这样使用它:
Dict d = new Dict();
d.Add("key", "value");
Can I create analiasimilar to this in Java?
When the type name is too long, in C# i can create alias like this:
using Dict = System.Collections.Generic.Dictionary<string, string>;
And I can use it like this:
Dict d = new Dict();
d.Add("key", "value");
Can I create an alias similar to this in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法创建别名,但可以
导入
包 (JLS 7.5 导入声明),这样您就不必完全限定该包中的类名。您还可以执行
静态导入
(指南),尽管这种做法应该受到限制。You can't create an alias, but you can
import
packages (JLS 7.5 Import Declarations) so that you don't have to fully qualify class names in that package.You can also do a
static import
(guide), though this practice should be limited.简短的回答:不。
但是,您可以(并且应该)
导入
类,以便不使用其完全限定名称:如果您必须定义别名,因为您的类正在使用多级泛型或除此之外,您可以使用此技巧 - 通过定义一个私有类来扩展您要别名的类(包括泛型),只是为了拥有一个易于使用的句柄:(在
作为 Java 的增强,且仍在等待中)
Short answer: nope.
However, you can (and should)
import
classes so as to not use their fully qualified name:If you must define an alias since your class is using multi-level generics or whatnot, you can use this hack - by defining a private class which extends the class you're aliasing (generics included) just for the sake of having an easy-to-use handle:
(adding class aliases was requested before as an enhancement to Java, and is still pending)
不,你不能在java中这样做。这里你需要导入包,如果你不想导入包那么你需要使用完全限定的类名。
No you can not do like that in java.Here you need to import the packages, if you do not want to import the package then you need to use fully qualified class name.
我赞同尤瓦尔的子类技巧。这在性能或语义上并不是什么大问题。
在 C# 中,Dictionary也是一种NEW类型;泛型类型的每个实例化都会在运行时创建一个新类。
I second Yuval's subclass trick. It's not a big deal in performance or semantics.
In C#, Dictionary<string, string> is also a NEW type; each instantiation of a generic type creates a new class at runtime.