jeudi 23 mars 2017

Checking if a Class?> is instane of other by reflection

I'm trying to create a random generator of any class for stress test purposes.

My generator goals to create any class with default constructor and fill its primitive and String fields (by reflection)

I would like also to fill fields of type Number (Integer, Long, Double....) as they are easily convertible to primitives.

But I couldn't find a simple approach o instanceof between types.

Here is the method

public static <V> Collection<V> createMassiveCollection(Class<V> clazz, int amount, Class<?> collectionType) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

        Random r = new Random();
        RandomGenerator rg = new RandomGenerator();
        @SuppressWarnings("unchecked")
        Collection<V> collection = (Collection<V>) collectionType.newInstance();
        for (int i = 0; i < amount; i++) {
            V item = clazz.newInstance();

            for (Field field : item.getClass().getDeclaredFields()) {

                if (java.lang.reflect.Modifier.isStatic(field.getModifiers()) || java.lang.reflect.Modifier.isFinal(field.getModifiers()))
                    continue;

                field.setAccessible(true);

                if (field.getType().equals(String.class))
                    field.set(item, rg.nextCompliment());

                else if (field.getType().isPrimitive() && (field.getType() != boolean.class && field.getType() != byte.class && field.getType() != char.class))
                    field.set(item, r.nextInt(1000000));

                else {
                    Constructor<?> c = null;

                    try {
                        c = field.getType().getConstructor(String.class);
                    }
                    catch (Exception e) {}
                    if (c != null && Number.class.isInstance(c.newInstance("1")))
                        field.set(item, field.getType().getConstructor(String.class).newInstance(r.nextInt(1000000) + ""));
                }

            }

            collection.add(item);
        }
        return collection;
    }

The third if is the one causing problems I would like something like: "if Type<C> is subtype of Type<V>" but all ways i found need an valid instance of object to check.

ex. Number.class.isInstance(field.getType()) nor field.getType() instanceof Number works because field.getType() is instance of Type.

Does anyone know if it is possible?

Another question (less important) in my method signature i would like to have

Class<? extends Collection<V>> collectionType

but if i do that when i try to call the method like

createMassiveCollection(User.class, 100000, new ArrayList<User>().getClass());

the compiler fails! so, to be able to compile i must trust the user is passing some type that extends Collection as parameter





Aucun commentaire:

Enregistrer un commentaire