开发者

"using" directive in Java

开发者 https://www.devze.com 2022-12-22 16:14 出处:网络
When the type name is too long, in C# i can create alias like this: using Dict = System.Collections.Generic.Dictionary<string, string>;

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 creat开发者_JAVA技巧e an alias similar to this in Java?


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


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)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号