Short name for imported constant class fields

2020-04-12 04:39发布

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?

3条回答
地球回转人心会变
2楼-- · 2020-04-12 04:44

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.*;

查看更多
啃猪蹄的小仙女
3楼-- · 2020-04-12 04:52

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

import static mynamespace.MyClassConstants.*;

See also:

查看更多
够拽才男人
4楼-- · 2020-04-12 04:57

try

import static mynamespace.MyClassConstants.*;

then

myMethod( C1, C2 );  should work
查看更多
登录 后发表回答