xvik / generics-resolver

Java generics runtime resolver
https://xvik.github.io/generics-resolver
MIT License
46 stars 9 forks source link

ConstructorGenericsContext.parameterType(i) fails for primitive parameter. #5

Closed UnasZole closed 4 years ago

UnasZole commented 4 years ago

To reproduce : GenericsResolver.resolve(Integer.class).constructor(Integer.class.getConstructors()[0]).parameterType(0)

This throws : java.lang.IllegalArgumentException: Type int is not assignable from java.lang.Integer at ru.vyarus.java.generics.resolver.context.GenericsInfo.getTypeGenerics(GenericsInfo.java:61) at ru.vyarus.java.generics.resolver.context.AbstractGenericsContext.<init>(AbstractGenericsContext.java:64) at ru.vyarus.java.generics.resolver.context.GenericsContext.<init>(GenericsContext.java:47) at ru.vyarus.java.generics.resolver.context.GenericsContext.inlyingType(GenericsContext.java:179) at ru.vyarus.java.generics.resolver.context.ConstructorGenericsContext.parameterType(ConstructorGenericsContext.java:146)

Error seems apparent when debugging the library :

xvik commented 4 years ago

Thank you very much! I checked primitives behavior for all resolution methods and updated javadoc to clearly state it.

In this exact case, of course new context must be created for wrapper (it is easy to recognize primitive manually if required). Now all such cases should be fixed. I will release 3.0.2 hotfix today.

UnasZole commented 4 years ago

Thanks !

Indeed, it's easy enough to check for primitive type, but this means that currently in my code I have a bunch of places where I need to do :

     if(paramType instanceof Class && ((Class)paramType).isPrimitive()) {
        // If parameter is of primitive type, genericsContext must not be used.
        // (see https://github.com/xvik/generics-resolver/issues/5). Use null.
        paramContext = null;
      }
      else {
        // Else, get generic context for parameter.
        paramContext = genericsContext.parameterType(i);
      }

Don't you think it would be useful to update the parameterType method (and others in the same case) so that it returns null instead of throwing an exception ? :-)

xvik commented 4 years ago

Methods like parameterType must not throw exception now, instead, it will return context for wrapper type (kind of autoboxing).

By "easy enough to check for primitive type" I mean that it's easy to detect such "autoboxing". case

UnasZole commented 4 years ago

Ah, ok. It's all good then, thanks a lot !