For my project, I have many objects, divided into 10 classes. Each of the objects can perform some operations that must be registered in advance (registration of operations is performed only once for each class). The operations defined for each class are represented as public final staticintegers. I would like to dynamically assign an identifier for operations at runtime (the number of operations per class is currently around 20, and the number will increase).
The problem arises when the operation is executed, and I have to find which operation is performed (I use the switch statement).
Here is a simple working code example:
public class Test {
final static int foo = 8;
final static int bar = 10;
public static void main(String[] args)
{
int x=10;
switch(x)
{
case foo:
System.out.println("FOO");
break;
case bar:
System.out.println("BAR");
break;
default:
System.out.println("PROBLEM");
}
}
}
This code is usually compiled and displayed BAR.
Unresolved compilation problem case expressions must be constant expressions.
public class Test {
final static int foo;
final static int bar;
static
{
foo=8;
bar=10;
}
public static void main(String[] args)
{
int x=10;
switch(x)
{
case foo:
System.out.println("FOO");
break;
case bar:
System.out.println("BAR");
break;
default:
System.out.println("PROBLEM");
}
}
}
?
, ? ?
EDIT:
- :
public class Test {
enum OperationSet1 {
FOO, BAR, THESE, ARE, ALL, DIFFERENT, OPERATIONS
}
enum OperationSet2 {
FOO, BAR, NOW, SOME, OTHER, OPS
}
public static void main(String[] args) {
OperationSet1[] ops = new OperationSet1[10];
for (int i=0; i<ops.length; i++)
ops[i] = OperationSet1.values()[(int)(Math.random()*OperationSet1.values().length)];
OperationSet2[] ops2 = new OperationSet2[10];
for (int i=0; i<ops.length; i++)
ops[i] = OperationSet2.values()[(int)(Math.random()*OperationSet2.values().length)];
for (OperationSet1 op:ops)
handleOperation(op);
}
for (OperationSet2 op:ops2)
handleOperation(op);
}
public static void handleOperation(Object? op) {
switch(op) {
}
}
}
, ( switch), , .
EDIT2:
. 10 (C1, C2, ..., C10) 40 . , . ( - Java).
obj , obj own, ( ), ( ). obj , , C1 enum. , own C1. obj2, C2, own. obj , C1, obj2 , C2.
, ? ?