Julez
Julez

Reputation: 1050

Pass Field Type as Class<T>

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.

Upvotes: 0

Views: 768

Answers (3)

Julez
Julez

Reputation: 1050

Thank you for trying to help me. I, however, bumped into the luck. I just changed:

type.getClass()

to

type.toString().getClass()

Upvotes: 1

davidxxx
davidxxx

Reputation: 131346

Field::getType returns a class. Why storing it into an Object in your collected stream ? Just collect them into a List of class.
Besides the parameterized type method scoped is helpless here. You don't want to infer any type.

That would give :

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

Note that you collect declared fields and then you seem to want to use them in the method retrieved by reflection. What is not very clear.

Upvotes: 2

Try changing

public <T> List<Object>

By

public <T> List<T>

Upvotes: 0

Related Questions