var blks = ReflectionHelper.getClasses("PACKAGE_NAME"); var blockRta = RuntimeTypeAdapterFactory.of(Block.class); for (var c : blks) { if (Block.class.isAssignableFrom(c)) { blockRta.registerSubtype(c); } }
I got Warning:(31, 46) Unchecked assignment: 'java.lang.Class' to 'java.lang.Class<? extends PACKAGE_NAME.Block>'
warning on the line blockRta.registerSubtype(c);
, but I can’t figure out how to fix that without supressing it.
ReflectionHelper.getClasses
is a static method to get all the classes in that package name, and its return type is Class[]
. Block
is an interface. RuntimeTypeAdapterFactory
is a class in gson extra, and its source code can be viewed here.
Advertisement
Answer
Since ReflectionHelper.getClasses
returns an array of the raw type Class
, the local-variable type inference will use this raw type Class[]
for var blks
and in turn, the raw type Class
for var c
. Using the raw type Class
for c
allows passing it to registerSubtype(Class<? extends Block>)
, without any check, but not without any warning. You can use the method asSubclass
to perform a checked conversion, but you have to declare an explicit non-raw variable type, to get rid of the raw type, as otherwise, even the result of the asSubclass
invocation will be erased to a raw type by the compiler.
There are two approaches. Change the type of blks
:
Class<?>[] blks = ReflectionHelper.getClasses("PACKAGE_NAME"); var blockRta = RuntimeTypeAdapterFactory.of(Block.class); for(var c: blks) { if (Block.class.isAssignableFrom(c)) { blockRta.registerSubtype(c.asSubclass(Block.class)); } }
Then, the type of var c
changes automatically to Class<?>
.
Or just change the type of c
:
var blks = ReflectionHelper.getClasses("PACKAGE_NAME"); var blockRta = RuntimeTypeAdapterFactory.of(Block.class); for(Class<?> c: blks) { if (Block.class.isAssignableFrom(c)) { blockRta.registerSubtype(c.asSubclass(Block.class)); } }