“using” directive in Java

让人想犯罪 __ 提交于 2019-12-08 20:33:13

问题


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?


回答1:


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));



回答2:


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)




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/2413606/using-directive-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!