vendredi 21 décembre 2018

Pass Field Type as Class

I have the following codes.

public <T> List<Object> types(Class<T> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        List<Object> types = Arrays.stream(fields)
                .map(Field::getType)
                .collect(Collectors.toList());
        return types;
}

I am struggling as how I would pass the field type as Class object later on. I'll be using them in the reflection (clazz here is class Contact):

for (Object type : name(clazz)) {
            Method method = obj.getClass().getDeclaredMethod("myMethod", type.getClass());
}

Assuming that type is a String, if I print it out as: System.out.println(type); output is: class java.lang.String but if I print it as: System.out.println(type.getClass(); output is: class java.lang.Class. So if I pass it as type.getClass(), reflection complains:

java.lang.NoSuchMethodException: Contact.myMethod(java.lang.Class)

Please help. Thanks.





Aucun commentaire:

Enregistrer un commentaire