Использование Reflection
может упростить конструкцию. Предположим, вы хотите вызвать метод setVn
в соответствии с перечислением EnumFields
, метод может быть получен из класса Reflection
и может быть вызван.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Class1 {
// Enum to be used to index each variable
public enum EnumFields {
ENUM_V1, ENUM_V2, ENUM_V3,
}
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
String[] arrayStr = new String[EnumFields.values().length];
for (int i = 0; i < arrayStr.length; i++) {
arrayStr[i] = String.valueOf(i);
}
Class1 class1 = new Class1(arrayStr);
System.out.println(class1.v1);
System.out.println(class1.v2);
System.out.println(class1.v3);
}
private String v1;
private String v2;
private String v3;
public Class1(String[] arrayStr) throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
for (EnumFields enumField : EnumFields.values()) {
Method setMethod = Class1.class.getDeclaredMethod("setV" + (enumField.ordinal() + 1), String.class);
setMethod.invoke(this, arrayStr[enumField.ordinal()]);
}
}
private void setV1(String v) {
this.v1 = v;
}
private void setV2(String v) {
this.v2 = v;
}
private void setV3(String v) {
this.v3 = v;
}
}