java, is there a way we can import a class under another name

青春壹個敷衍的年華 提交于 2019-12-22 01:23:10

问题


is there a way we can import a class under another name? Like if i have a class called javax.C and another class called java.C i can import javax.C under the name C1 and import java.C under the name C2.

We can do something like this in C#:

using Sys=System;

or Vb:

Imports Sys=System

回答1:


No, there is nothing like that in Java. You can only import classes under their original name, and have to use the fully qualified name for all that you don't import (except those in java.lang and the current class's package).




回答2:


To be short, no, this isn't possible in Java.




回答3:


No. I think Java deliberately ditched typedef. The good news is, if you see a type, you know what it is. It can't be an alias to something else; or an alias to an alias to ...

If a new concept really deserves a new name, it most likely deserves a new type also.

The usage example of Sys=System will be frowned upon by most Java devs.




回答4:


Java doesn't support static renaming. One idea is to subclass object in question with a new classname (but may not be a good idea because of certain side-effects / limitations, e.g. your target class may have the final modifier. Where permitted the code may behave differently if explicit type checking is used getClass() or instanceof ClassToRename, etc. (example below adapted from a different answer)

class MyApp {

  public static void main(String[] args) {
    ClassToRename parent_obj = new ClassToRename("Original class");
    MyRenamedClass extended_obj_class_renamed = new MyRenamedClass("lol, the class was renamed");
    // these two calls may be treated as the same
    // * under certain conditions only *
    parent_obj.originalFoo();
    extended_obj_class_renamed.originalFoo();
  }  

  private static class ClassToRename {
    public ClassToRename(String strvar) {/*...*/}
    public void originalFoo() {/*...*/}
  }

  private static class MyRenamedClass extends ClassToRename {
    public MyRenamedClass(String strvar) {super(strvar);}
  }

}


来源:https://stackoverflow.com/questions/5767864/java-is-there-a-way-we-can-import-a-class-under-another-name

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