GentyRef framework in the JAV class library's technical problems and solution principles
Gentyref framework is a genetic inference and reconstruction for Java class libraries.It solves some common problems that may occur when using generic type inferring in Java.This article will introduce the technical problems of the Gentyref framework in the Java library, and provide the corresponding solution principles and Java code examples.
1. Can't correctly infer the generic type
The type of Java can not be accurately inferred in some cases.For example, when an anonymous internal class is used, the compiler cannot determine the specific type parameters.At this time, you can use the GentyRef framework to expand the specified type parameter to avoid the problem of type inference.
Example code:
List<String> list = new ArrayList<String>() {};
TypeRef<List<String>> typeRef = new TypeRef<List<String>>() {};
In the above example, by using the TypereF class of the Gentyref framework, we can specify the generic type parameters when the anonymous internal class is not explicitly written.
2. Loss of generic parameters
Sometimes, when the generic type is obtained by reflection, the information of the type parameters will be lost.For example, when we get the return type from a generic method, the return type will lose the specific type information of the generic parameters.Using the GentyRef framework can solve this problem, to obtain specific type parameter information by providing a context with generic parameters.
Example code:
class MyClass<T> {
public List<T> getList() {
return null;
}
}
Method method = MyClass.class.getMethod("getList");
Class<?> returnType = method.getGenericReturnType();
TypeRef<?> typeRef = TypeRef.newTypeRef(returnType);
System.out.println(typeRef.getActualTypeArguments()[0]);
In the above example, we use the TypereF class of the Gentyref framework to obtain the specific type parameters of the type method returned.
3. Type erased problems
The generic types in Java will be erased after compiling, causing the specific information of the genetic parameters during runtime.Gentyref framework solves this problem by maintaining a type of reference tree.Through recursively traversing type reference trees, you can obtain specific type information of generic parameters at runtime.
Example code:
class MyClass<T> {
public void doSomething(List<T> list) {
TypeRef<?> typeRef = new TypeRef<List<T>>() {};
System.out.println(typeRef.getActualTypeArguments()[0]);
}
}
In the above example, we obtained the specific type information of the generic parameter through the TypereF class of the Gentyref framework at runtime, that is, the type of T.
Gentyref frameworks have facilitated the use of genetic parameters, loss of type parameters, and type erasers, which provide convenience.Through the above technical problems and the introduction of the principle of solution, we can better understand the role and usage of the Gentyref framework in the Java library.