I'm writing code that reads values from props file and attempts to automatically create corresponding POJO instance.
// 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);
}
}
The code above will retrieve the 'key' of any field annotated with @PropXFileRWBindByName and will then retrieve the value from properties file. It then attempts to create instance of given object using newInstance(objs);
The issue is that I want to enforce the order of arguments in the constructor. In other words, the keys are being retrieved in the same order they appear in class. Obviously, when I initially created the constructor the order of arguments mimicked the order they appear in class. But how can I enforce this so that it the order of arguments in constructor always matches the order I get in keys
? In other words, I want to enforce that the constructor arguments must always appear in a specific order (perhaps via annotations?) so that if they are changed IDE should display error.
In my specific example constructor looks something like this:
constructor(String str1, String str2, String str3, ArrayList<String> arr1, ArrayList<String> arr2, String str4)
When I retrieve values from file I need to know the exact order of arguments and generate constructor accordingly.
My question is how can I enforce that order of arguments in constructor is always consistent with the way they appear in class so I match the arguments correctly when creating new instance via Reflection
?
Thanks!
Aucun commentaire:
Enregistrer un commentaire