Add a variable to a class instance at runtime: Difference between revisions

Content added Content deleted
(New post.)
Line 677: Line 677:
W__OBJ2 NB. our other instance does not
W__OBJ2 NB. our other instance does not
|value error</syntaxhighlight>
|value error</syntaxhighlight>

=={{header|Java}}==
Adding variables to an object at runtime is not possible in Java which is a statically typed language requiring the names of all class variables to be known at compile time.

However, we can make it appear as though variables are being added at runtime by using a Map or similar structure.
<syntaxhighlight lang="java">
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public final class AddVariableToClassInstanceAtRuntime {

public static void main(String[] args) {
Demonstration demo = new Demonstration();
System.out.println("Create two variables at runtime: ");
Scanner scanner = new Scanner(System.in);
for ( int i = 1; i <= 2; i++ ) {
System.out.println(" Variable number " + i + ":");
System.out.print(" Enter name: ");
String name = scanner.nextLine();
System.out.print(" Enter value: ");
String value = scanner.nextLine();
demo.runtimeVariables.put(name, value);
System.out.println();
}
scanner.close();
System.out.println("Two new runtime variables appear to have been created.");
for ( Map.Entry<String, Object> entry : demo.runtimeVariables.entrySet() ) {
System.out.println("Variable " + entry.getKey() + " = " + entry.getValue());
}
}

}

final class Demonstration {
Map<String, Object> runtimeVariables = new HashMap<String, Object>();
}
</syntaxhighlight>
{{ out }}
<pre>
Create two variables at runtime:
Variable number 1:
Enter name: Test
Enter value: 42

Variable number 2:
Enter name: Item
Enter value: 3.14

Two new runtime variables appear to have been created.
Variable Item = 3.14
Variable Test = 42
</pre>


=={{header|JavaScript}}==
=={{header|JavaScript}}==