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. So when Java compiles, is it possible to have Java use the System Environment variable to determine the type at compile type?
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?
I have an idea.
Make the testVariable
of type Object
(or a DummyType
class which extends Object
). 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.
And you can also set the value of the testVariable
upon initialization as appropriate, naturally.
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:
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With