Difference between

extends The wildcard declaration of List<? extends Number> foo3 means that any of these are legal assignments: List<? extends Number> foo3 = new ArrayList<Number>(); // Number “extends” Number (in this context) List<? extends Number> foo3 = new ArrayList<Integer>(); // Integer extends Number List<? extends Number> foo3 = new ArrayList<Double>(); // Double extends Number Reading – … Read more

Get generic type of class at runtime

As others mentioned, it’s only possible via reflection in certain circumstances. If you really need the type, this is the usual (type-safe) workaround pattern: public class GenericClass<T> { private final Class<T> type; public GenericClass(Class<T> type) { this.type = type; } public Class<T> getMyType() { return this.type; } }

Protocol doesn’t conform to itself?

Why don’t protocols conform to themselves? Allowing protocols to conform to themselves in the general case is unsound. The problem lies with static protocol requirements. These include: static methods and properties Initialisers Associated types (although these currently prevent the use of a protocol as an actual type) We can access these requirements on a generic … Read more

How do I use reflection to call a generic method?

You need to use reflection to get the method to start with, then “construct” it by supplying type arguments with MakeGenericMethod: MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod)); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null); For a static method, pass null as the first argument to Invoke. That’s nothing to do with generic methods – it’s just normal reflection. … Read more