How to create dynamic variables in Java?

For example, in Haxe I can create strongly typed variables: var a:Float = 1.1; or var b:String = "hello" , as well as dynamic, if necessary:

var d:Dynamic = true; d = 22; d = "hi";

How to create this type of variables in Java?

+5
source share
3 answers

You can use Object

 Object d = true; d = 22; d = "hi"; 

and you can use instanceof operator to check which data type d contains

 Object d = true; System.out.println(d instanceof Boolean); // true d = 22; d = "hi"; System.out.println(d instanceof Integer); // false System.out.println(d instanceof String); // true 

The Type Comparison Operator instanceof

+11
source

Dynamic typing is evil, so Java avoided this. Like Swift and C #, Java is strongly typed, which leads to safer and cleaner code. So go to the dark side and put off your rebellious paths. Declare the Power of Program Oriented Programming. You will be better for this.

+1
source

You can look at mixing in groovy, which runs on the JVM. It has an inferrance type

+1
source

Source: https://habr.com/ru/post/1265250/


All Articles