1
Class clazz = parameter.getParameterType();

Here I have clazz, which i'm certain that this is Optional<T> type class. The problem is how can I get this T? I want to know if this is String or Long or Integer or something in the runtime.

ok, I think I didn't put it clearly. I got a method parameters by reflection,

public String abc(Optional<String> ttt, Optional<Integer> bbb) {
    return;
}

So now I have the class of ttt, and bbb, and i'm sure that this is Optional<T>.class, but can I get which T elasctly that is.

Kim
  • 5,045
  • 6
  • 38
  • 60

1 Answers1

5

You cannot. At runtime, Java doesn't even know the actual generic type.

If the Optional is present, you can do optional.get().getClass(), but if the optional is absent there is absolutely no way to tell whether it is an Optional<String>, Optional<Integer>, or Optional<NuclearMissile>.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413