NOVA-Team / NOVA-Monorepo

The core API of the NOVA voxel game modding system
https://nova-team.github.io
GNU Lesser General Public License v3.0
66 stars 23 forks source link

Use a Generic Type Resolver to remove redundant calls to Factory.build().getClass() #292

Closed ExE-Boss closed 7 years ago

ExE-Boss commented 7 years ago

A Generic Type Resolver is a piece of software which can resolve Java’s Generic Types. Contrary to popular belief, Java doesn’t completely remove all generic types during runtime. In the following example:

class GenericExample<T> {
}

class Example extends GenericExample<String> {
}

It is possible to resolve the generic type T of the class Example with the following code:

Class<?> genericType = ((ParameterizedType) Example.class.getGenericSuperclass()).getActualTypeArguments()[0];

During runtime, genericType will return String.class This code is however capable of throwing a ClassCastException and can only resolve the type of the immediate superclass.

To resolve the generic type of a class higher in the hierarchy and to protect ourselves from ClassCastExceptions, we need to use some generic type resolver.

A good generic type resolver is the typetools and one of it’s greatest features are the abilities to resolve lambda generics and generic types of classes higher in the hierarchy. It's available on the Maven Central repository as the following dependency:

dependencies {
    compile 'net.jodah:typetools:0.4.9'
}