Short name for imported constant class fields

余生颓废 提交于 2019-12-01 23:23:24

问题


I have a java program with hundreds of configuration constants:

public static final String C1="C1";
public static final String C2="C2";

Since there are so many of them, I've put them into a separate class, MyClassConstants. Now, I need to use them on MyClass:

import mynamespace.MyClassConstants;
myMethod( MyClassConstants.C1, MyClassConstants.C2 );

This gets very verbose very fast, so I was wondering if it was possible to somehow import the fields directly:

import mynamespace.MyClassConstants.*; 
myMethod( C1, C2 ); //doesn't work

Or at the very least, rename the import:

import mynamespace.MyClassConstants as C; //javac hates me
myMethod( C.C1, C.C2 );

But it seems this later approach is impossible

Is there a way to do this and still have a meaningful class name for the constants? Or should I use another approach?


回答1:


The answer is Static import, you can solve by using it:

import static mynamespace.MyClassConstants.*;

See also:

  • Static import
  • Java doc: static import



回答2:


try

import static mynamespace.MyClassConstants.*;

then

myMethod( C1, C2 );  should work



回答3:


You should static import. More details are here http://javapapers.com/core-java/what-is-a-static-import-in-java/

You have it like : import static mynamespace.MyClassConstants.*;



来源:https://stackoverflow.com/questions/19134577/short-name-for-imported-constant-class-fields

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