“使用” Java 中的指令

发布于 2024-08-24 16:54:16 字数 275 浏览 4 评论 0原文

当类型名称太长时,在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

眼角的笑意。 2024-08-31 16:54:16

您无法创建别名,但可以导入包 (JLS 7.5 导入声明),这样您就不必完全限定该包中的类名。

import java.util.*;
import java.lang.reflect.Field;

....

Set<Field> s = ... // Set is in java.util

您还可以执行静态导入 (指南),尽管这种做法应该受到限制。

import static java.util.Arrays.asList;

...

System.out.println(asList(1, 2, 3));

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.

import java.util.*;
import java.lang.reflect.Field;

....

Set<Field> s = ... // Set is in java.util

You can also do a static import (guide), though this practice should be limited.

import static java.util.Arrays.asList;

...

System.out.println(asList(1, 2, 3));
友谊不毕业 2024-08-31 16:54:16

简短的回答:

但是,您可以(并且应该)导入类,以便不使用其完全限定名称:

import java.lang.String
// ....
String s = "hello, world.";

如果您必须定义别名,因为您的类正在使用多级泛型或除此之外,您可以使用此技巧 - 通过定义一个私有类来扩展您要别名的类(包括泛型),只是为了拥有一个易于使用的句柄:(在

class MyMap extends HashMap<String, String> {}
        
MyMap a = new MyMap();
a.put("key", "val");

作为 Java 的增强,且仍在等待中)

Short answer: nope.

However, you can (and should) import classes so as to not use their fully qualified name:

import java.lang.String
// ....
String s = "hello, world.";

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:

class MyMap extends HashMap<String, String> {}
        
MyMap a = new MyMap();
a.put("key", "val");

(adding class aliases was requested before as an enhancement to Java, and is still pending)

一枫情书 2024-08-31 16:54:16

不,你不能在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.

宫墨修音 2024-08-31 16:54:16

我赞同尤瓦尔的子类技巧。这在性能或语义上并不是什么大问题。

在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文