Skip to content

Instantly share code, notes, and snippets.

@theotherian
Last active December 19, 2015 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theotherian/5953709 to your computer and use it in GitHub Desktop.
Save theotherian/5953709 to your computer and use it in GitHub Desktop.
Constants and how they can be misleading
Sample code for ways Java Constants may not work as you would expect
public class App {
public static void main(String[] args) {
System.out.println(MyAnnotatedClass.class.getAnnotation(MyAnnotation.class).value());
System.out.println(Constants.OUTPUT_DIRECTORY);
}
}
public class Constants {
// if you're wondering where the drive letter is, you have more reading to do :)
public static final String OUTPUT_DIRECTORY = "/opt/application-output";
}
@MyAnnotation(Constants.OUTPUT_DIRECTORY)
public class MyAnnotatedClass {
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
$ tree
.
|____App.java
|____Constants.java
$ javac -cp . *.java
$ tree
.
|____App.class
|____App.java
|____Constants.class
|____Constants.java
$ java -cp . SimpleApp
/opt/application-output
$ rm Constants.class
$ java -cp . SimpleApp
/opt/application-output
public class SimpleApp {
public static void main(String[] args) {
System.out.println(Constants.OUTPUT_DIRECTORY);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment