简体   繁体   English

编译时的原始变量类型

[英]Primitive variable type in compile time

Not sure if I am wording this correctly. 不确定我是否正确措辞。 Please let me know if you require more information. 如果您需要更多信息,请与我们联系。 We have a requirement where we need to determine the type of variable based on a system environment variable. 我们需要根据系统环境变量确定变量的类型。

So, say we have a the following class 所以,假设我们有以下课程

class Test
{
    DUMMY_TYPE testVariable;
}

The DUMMY_TYPE is determined based on a system variable. DUMMY_TYPE基于系统变量确定。 So when Java compiles, is it possible to have Java use the System Environment variable to determine the type at compile type? 因此,当Java编译时,是否可以让Java使用System Environment变量来确定编译类型的类型?

Also, is it possible to set this up somehow on Eclipse, where Eclipse will continue to show me DUMMY_TYPE on the IDE wherever I use it, but when compiling and building it can substitute DUMMY_TYPE with the correct type based on environment variable? 另外,是否可以在Eclipse上以某种方式设置它,Eclipse将继续在IDE上向我显示DUMMY_TYPE,无论我在何处使用它,但是在编译和构建它时,可以使用基于环境变量的正确类型替换DUMMY_TYPE?

I have an idea. 我有个主意。

Make the testVariable of type Object (or a DummyType class which extends Object ). testVariable Object类型的testVariable (或扩展ObjectDummyType类)。 Then you can load the variable with whatever data you want using the primitive wrapper classes, based 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 isn't Java "figuring out" which type it is at compile time like you want, necessarily (and the assignment would take place at run time, when the Test object was created), but it seems like reasonable framework for an alternative. 当然,这不是Java“搞清楚”它在编译时的类型是你想要的,必然(并且在创建Test对象时,分配将在运行时进行),但它似乎是合理的框架替代。

And you can also set the value of the testVariable upon initialization as appropriate, naturally. 您也可以在初始化时自然地设置testVariable的值。

Alternatively, you could have a method like this which accepts inputs as a String (read from your system variable) and returns it in the appropriate wrapper class of the primitive type: 或者,您可以使用这样的方法接受输入作为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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM