Im trying to write a function that given a class it will build an object of that type (using reflection). Its working so far but im having trouble with Collections as members.
public static <T> T object(Class<T> type) throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
T object = getNullInstanceOf(type);
List<Field> fields = Arrays.asList(object.getClass().getDeclaredFields());
for (Field f : fields) {
f.setAccessible(true);
if (Modifier.isFinal(f.getModifiers())) {
continue;
}
try {
Object fieldValue = f.get(object);
if (f.getType().equals(CharSequence.class) || f.getType().equals(String.class)) {
f.set(object, f.getName());
} else if (f.getType().equals(Integer.TYPE)) {
f.set(object, 1);
} else if (f.getType().equals(Double.TYPE)) {
f.set(object, 2.0);
} else if (f.getType().equals(Long.TYPE)) {
f.set(object, 3L);
} else if (isClassCollection(f.getType())) {
f.set(object,
((Collection) getNullInstanceOf(f.getType())) // this throws a "No Such Method Exists" Exception
.add(object(f.getGenericType().getClass())));
} else if (!(f.getType().equals(type))) {
f.set(object, object(f.getType()));
} else {
return null;
}
} catch (Exception e) {
System.err.println("Could not access:" + f.getName());
continue;
}
}
return object;
}
public static boolean isClassCollection(Class<?> c) {
return Collection.class.isAssignableFrom(c)
|| Map.class.isAssignableFrom(c);
}
private static <T> T getNullInstanceOf(Class<T> type) throws InvocationTargetException, InstantiationException,
IllegalAccessException, NoSuchMethodException, ClassNotFoundException {
Class<?> clazz = Class.forName(type.getName());
Constructor<?> ctor = clazz.getConstructor();
return (T) ctor.newInstance();
}
}
The issue im having is that when I try to create an instance of the collection, whether it be a set, list, or map, those classes are abstract. Is there a way to just pick a random implementation or do I have to hardcode a concrete subclass for every abstract class?
Aucun commentaire:
Enregistrer un commentaire