andy
andy

Reputation: 1356

Spring Contants will ignore not all upper case field

If a class have some public static final fields, then spring Contants class can help to provide help to these fields.

But for lower case field name, Contants not handle well. Java specification suggestion that we use all upper case for public static final fields name, but lower case name still valid.

see example:

public class Test {
    public static final int a = 1;
    public static final int B = 2;

    public static void main(String[] args) {
        org.springframework.core.Constants constants = new org.springframework.core.Constants(Test.class);
        System.out.println(constants.asNumber("b").intValue()); // line 1
        System.out.println(constants.asNumber("a").intValue()); // line 2
    }
}

line 1 will output 2, but line 2 will throw ConstantException: Field 'A' not found in class Test

Why does not they compare them case sensitive?

Upvotes: 1

Views: 53

Answers (1)

Boris the Spider
Boris the Spider

Reputation: 61198

Because of convention, compile time constants in Java are always is UPPER_UNDERSCORE. No exceptions.

From the documentation for Constants

Consider class Foo containing public final static int CONSTANT1 = 66; An instance of this class wrapping Foo.class will return the constant value of 66 from its asNumber method given the argument "CONSTANT1".

So while a name in camelCase or (heaven forbid) lower_underscore is valid according to the Java programming language; is it against accepted convention and not to be encouraged.

Upvotes: 1

Related Questions