我的班级目前看起来像这样:
@Getter
@Setter
public class Class1 {
private String v1;
private String v2;
private String v3;
...
//Enum to be used to index each variable
public enum EnumFields
{
ENUM_V1,
ENUM_V2,
ENUM_V3,
...
...
}
public Class1(String[] arrayStr) {
setV1(arrayStr[EnumFields.ENUM_V1.ordinal()]);
setV2(arrayStr[EnumFields.ENUM_V2.ordinal()]);
setV3(arrayStr[EnumFields.ENUM_V3.ordinal()]);
...
}
}
如何简化构造函数?有没有一种方法可以将set函数映射到每个枚举值并在for循环中调用它们?如果可以,怎么办?
谢谢, 斯瓦加蒂卡
答案 0 :(得分:0)
使用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;
}
}