如何在构造函数[Java]中强制参数顺序
我正在编写从props文件读取值并尝试自动创建相应的POJO实例的代码如何在构造函数[Java]中强制参数顺序,java,reflection,constructor,persistence,pojo,Java,Reflection,Constructor,Persistence,Pojo,我正在编写从props文件读取值并尝试自动创建相应的POJO实例的代码 // Code below will retrieve keys in order they are annotated in class.. this may or may not be same order as they appear in constructor.. (this is my problem) String[] keys = ReflectionX.getDeclaredMethodsWithPropX
// Code below will retrieve keys in order they are annotated in class.. this may or may not be same order as they appear in constructor.. (this is my problem)
String[] keys = ReflectionX.getDeclaredMethodsWithPropXFileRWBindByNameAnnotationSorted(c, PropXFileRWBindByName.class);
ArrayList<Object> objectList = new ArrayList<Object>();
// The code below retrieves String values from file
// I will repeat the code to retrieve ArrayList<String> values
for (String key : keys) {
String value = propsX.getPropValueAsStr(key);
objectList.add(value);
Constructor<?>[] constructors = c.getConstructors();
Object[] objs = objectList.toArray();
Constructor<?> finalConstructor = null;
for (Constructor<?> constructor : constructors) {
if (constructor.isAnnotationPresent(PropsXConstructor.class)) {
finalConstructor = constructor;
break;
}
}
if (finalConstructor != null) {
P record = (P) finalConstructor.newInstance(objs);
recordList.add(record);
}
}
当我从文件中检索值时,我需要知道参数的确切顺序,并相应地生成构造函数
我的问题是如何强制构造函数中的参数顺序始终与它们在类中的显示方式一致,以便在通过反射创建新实例时正确匹配参数
谢谢 但构造函数参数的顺序并没有改变,所以你们到底想在这里执行什么呢?我认为您所需要的只是编译器的一个标志来保留参数名,所以您可以只使用构造函数的参数。-parameters
keys
是一个仅在运行时存在的数组。您不能在编译时强制参数的顺序仅在运行时存在。只是想说明一下:规范中没有说明类文件中字段信息的顺序,也就是说,它不能保证反映源代码声明的顺序,因此由于类文件中不存在源代码顺序,ReflectionX.GetDeclaredMethodWithPropxFilerBindByNameAnnotationSorted
对它所做的任何事情都不能保证您按源代码顺序获取数组。
constructor(String str1, String str2, String str3, ArrayList<String> arr1, ArrayList<String> arr2, String str4)