1

Is it possible in Java to use variables value for type?

For example:

String s = "String";

And then I would create another variable z, which could use s value for his type. Is it possible to do that? Maybe with reflection or some other technique?

Update:

If it's not possible this way, maybe someone could suggest how to give type to variable, when you get what type it is from xml files attribute? Like

<tag type="String">MyValue</tag>

And then I could use type attributes value for defining variables type?

Andrius
  • 19,658
  • 37
  • 143
  • 243
  • You want to give the value of s to z? So that z would contain "String"? – Gábor Csikós Nov 09 '13 at 11:55
  • I want to when I create variable z, his type would be defined using variable's s value. Like s z; (just using s value as his type). – Andrius Nov 09 '13 at 11:56
  • That example you gave, still use which type it needs to have, like String and Integer. P.S Also why down vote? – Andrius Nov 09 '13 at 12:02
  • Suppose it's possible and now you have a variable called `z` with type `String`. What are you going to do with it? – Joni Nov 09 '13 at 12:10
  • @Joni use it as a parameter for method input value – Andrius Nov 09 '13 at 12:28
  • Then you have an additional problem: the method to be called is chosen by the compiler, and if the type of `z` is not known until the program is run it can't call the right method. What are you trying do really? – Joni Nov 09 '13 at 12:34
  • @Joni well, I have xml configuration file, which defined variable values and their types as attributes. And I need to use these in different methods, depending on their type. So I suppose I need to make some kind of loop, that would check if for example given value can be Integer, then make it Integer and only then use it for method right? – Andrius Nov 09 '13 at 12:38

2 Answers2

2

Do you look for something like this:

public static void main(String[] args) {
    String s = "java.lang.String";

    Object o = "Some Value";

    Class<?> type;
    try {
        type = Class.forName(s);
        getValue(type, o);
    } catch (ClassNotFoundException e) {
        // class was not found
        e.printStackTrace();
    }
}

private static <T> T getValue(Class<T> desiredType, Object o) {
    if (o.getClass().isAssignableFrom(desiredType)) {
        return desiredType.cast(o);
    } else {
        throw new IllegalArgumentException();
    }

}
markusw
  • 1,975
  • 16
  • 28
0

I know no language allowing it the way you wrote, and about other ways: you could achieve it with typedef in C or C++, but not in Java. However, you could often extend a class like this:

public class myName extends originalClassName {}

and then use myName instead of originalClassName. However, you can not do this with String, which is final and therefore can't be inherited after.

3yakuya
  • 2,622
  • 4
  • 25
  • 40