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

m
→‎{{header|Wren}}: Changed to Wren S/H
(Pascal entry)
m (→‎{{header|Wren}}: Changed to Wren S/H)
(2 intermediate revisions by 2 users not shown)
Line 340:
ELENA does not support adding a field at run-time but it can be simulated with the help of a mix-in.
 
ELENA 46.x:
<syntaxhighlight lang="elena">import extensions;
 
class Extender : BaseExtender
{
prop object foo : prop;
constructor(object)
{
this theObjectobject := object
}
}
 
public program()
{
var object := 234;
// extending an object with a field
object := new Extender(object);
 
object.foo := "bar";
 
console.printLine(object,".foo=",object.foo);
 
console.readChar()
}</syntaxhighlight>
{{out}}
Line 677:
W__OBJ2 NB. our other instance does not
|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}}==
Line 2,026 ⟶ 2,082:
=={{header|Wren}}==
Although Wren is dynamically typed, it is not possible to add new variables (or fields as we prefer to call them) to a class at run time. We therefore follow the example of some of the other languages here and use a map field instead.
<syntaxhighlight lang="ecmascriptwren">import "io" for Stdin, Stdout
 
class Birds {
9,485

edits