Convert from class to generic type

Hello, I am having an issue trying to take convert from a class to a generic type.

I have two methods, shown below:

Method 1:

public <T> boolean methodOne(Class<T> type, T value) {
  //Does stuff
}

Method 2:

public <T> boolean methodTwo(Object obj) {
  for (Field field : obj.getClass().getFields()) {
    //Doesn't work
    methodOne(field.getType(), field.get(obj));
  }
}

I am struggling to figure out how to convert from Class to Class<T> and Object to T. Is this even possible? Please let me know if you have a suggestion.

You could just ignore the generics completely and use the raw type

methodOne((Class) field.getType(), field.get(obj));

or this:

methodOne((Class<T>) field.getType(), (T) field.get(obj));
```
1 Like

@Flibio i think you should study the java trail section for Generics as it has good examples for that and as @simon816 said you could not use generics and still live :slightly_smiling:

Note that Java Generics are type erased at runtime, so even if the method signature takes a Class<T> and T object, due to type erasure, it just reads methodOne(Class type, Object value). This is why casting raw types still works in many ways, because all you have to do is just call methodOne(obj.getClass, obj).

But yes, as simon pointed out, all you have to do is cast.

1 Like

Thanks everyone!