3

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?

Community
  • 1
  • 1
loopbackbee
  • 21,962
  • 10
  • 62
  • 97

3 Answers3

6

try

import static mynamespace.MyClassConstants.*;

then

myMethod( C1, C2 );  should work
upog
  • 4,965
  • 8
  • 42
  • 81
6

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

import static mynamespace.MyClassConstants.*;

See also:

Rong Nguyen
  • 4,143
  • 5
  • 27
  • 53
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.*;

Lokesh
  • 7,810
  • 6
  • 48
  • 78