Primitive variable type at compile time

Not sure if this is formulated correctly. Please let me know if you need more information. We have a requirement when we need to determine the type of a variable based on a system environment variable.

So let's say we have the following class

class Test
{
    DUMMY_TYPE testVariable;
}

DUMMY_TYPE is determined based on a system variable. Therefore, when compiling Java, is it possible for Java to use the System Environment variable to determine the type in the compiler?

Also, is it possible to somehow configure this on Eclipse, where Eclipse will continue to show me DUMMY_TYPE in the IDE, wherever I use it, but when compiling and building can replace DUMMY_TYPE with the correct type based on the environment variable?

+5
source share
1 answer

I have an idea.

Make a testVariabletype Object(or a class DummyTypethat extends Object). You can then load the variable with whatever data you want using primitive wrapper classes, depending on what you read from your system variable.

So:

public class Test {

    Object testVariable;

    {
        String whichType = null;

        //Logic to read your system variable from wherever and store it in whichType

        if(whichType.equals("int")) {
            testVariable = new Integer(intVal);
        }
        else if(whichType.equals("double")) {
            testVariable = new Double(doubleVal);
        }
        //etc.
    }

Of course, this is not Java “figuring out” what type it is at compile time, as you want, it is necessary (and the assignment will be executed at runtime when the object was created Test), but it seems to be a reasonable basis for an alternative.

And you can also set the value testVariableduring initialization, if necessary, naturally.

, , String ( ) - :

public Object getPrimitiveValue(String type, String value) {
    if(type.equals("int")) {
        return new Integer(Integer.parseInt(value));
    }
    else if(type.equals("double")) {
        return new Double(Double.parseDouble(value));
    }
    //etc.
}
+1

All Articles