gpt4 book ai didi

java - 如何为 Java 类字段生成准确的泛型表达式?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:27:32 24 4
gpt4 key购买 nike

我正在尝试在运行时推理泛型。有几个很棒的库可以做到这一点(例如 gentyrefClassMateGuava)。然而,它们的用法有点让我难以理解。

具体来说,我想提取一个与子类上下文中的特定字段匹配的表达式。

这是一个使用 gentyref 的例子:

import com.googlecode.gentyref.GenericTypeReflector;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

public class ExtractArguments {

public static class Thing<T> {
public T thing;
}

public static class NumberThing<N extends Number> extends Thing<N> { }

public static class IntegerThing extends NumberThing<Integer> { }

public static void main(final String... args) throws Exception {
final Field thing = Thing.class.getField("thing");

// naive type without context
Class<?> thingClass = thing.getType(); // Object
System.out.println("thing class = " + thingClass);
Type thingType = thing.getGenericType(); // T
System.out.println("thing type = " + thingType);
System.out.println();

// exact types without adding wildcard
Type exactThingType = GenericTypeReflector.getExactFieldType(thing, Thing.class);
System.out.println("exact thing type = " + exactThingType);
Type exactNumberType = GenericTypeReflector.getExactFieldType(thing, NumberThing.class);
System.out.println("exact number type = " + exactNumberType);
Type exactIntegerType = GenericTypeReflector.getExactFieldType(thing, IntegerThing.class);
System.out.println("exact integer type = " + exactIntegerType);
System.out.println();

// exact type with wildcard
final Type wildThingType = GenericTypeReflector.addWildcardParameters(Thing.class);
final Type betterThingType = GenericTypeReflector.getExactFieldType(thing, wildThingType);
System.out.println("better thing type = " + betterThingType);
final Type wildNumberType = GenericTypeReflector.addWildcardParameters(NumberThing.class);
final Type betterNumberType = GenericTypeReflector.getExactFieldType(thing, wildNumberType);
System.out.println("better number type = " + betterNumberType);
final Type wildIntegerType = GenericTypeReflector.addWildcardParameters(IntegerThing.class);
final Type betterIntegerType = GenericTypeReflector.getExactFieldType(thing, wildIntegerType);
System.out.println("better integer type = " + betterIntegerType);
System.out.println();

System.out.println("desired thing type = T");
System.out.println("desired number thing type = N extends Number");
System.out.println("desired integer thing type = Integer");
}

}

这是输出:

thing class = class java.lang.Object
thing type = T

exact thing type = class java.lang.Object
exact number type = class java.lang.Object
exact integer type = class java.lang.Integer

better thing type = capture of ?
better number type = capture of ?
better integer type = class java.lang.Integer

desired thing type = T
desired number thing type = N extends Number
desired integer thing type = Integer

我知道 betterThingType Type 对象(一个 gentyref-specific implementation )比这里的 toString() 显示的更复杂。但我猜我需要使用非通配符 Type 再次调用 getExactFieldType 以获得我正在寻找的内容。

我的主要要求是我需要一个表达式,它可以成为代码生成的源文件的一部分,该文件可以成功编译——或者至少在进行最少修改的情况下编译。我愿意使用最适合这项工作的任何库。

最佳答案

要获得此类信息,您必须确定是否已将实际类型(例如 Integer)提供给泛型类型参数。如果不是,您将需要获取类型参数名称,因为它在您需要的类中已知,以及任何边界。

事实证明这很复杂。但首先,让我们回顾一下我们将在解决方案中使用的一些反射技术和方法。

首先, Field 's getGenericType() method返回 Type需要的信息。在这里,Type可以是一个简单的 Class如果提供了一个实际的类作为类型,例如Integer thing; , 或者它可以是 TypeVariable , 表示您在 Thing 中定义的通用类型参数,例如T thing; .

如果它是泛型,那么我们需要知道以下内容:

  • 这个类型最初是在哪个类中声明的。这是用 Field 's getDeclaringClass method 检索的.
  • 在每个子类中,来自声明 Field 的原始类, extends 中提供了哪些类型的参数条款。这些类型参数本身可能是实际类型,如 Integer ,或者它们可能是它们自己类的泛型类型参数。使事情复杂化的是,这些类型参数的名称可能不同,并且它们的声明顺序可能与父类(super class)中的顺序不同。 extends可以通过调用 Class 's getGenericSuperclass() method 来检索子句数据,它返回一个 Type这可以是一个简单的 Class ,例如 Object , 或者它可以是 ParameterizedType ,例如Thing<N>NumberThing<Integer> .
  • 可以使用 Class 's getTypeParameters() method 检索一个类自己的类型参数, 它返回 TypeVariable 的数组s.
  • 来自TypeVariable您可以提取名称,例如T和边界,作为 Type 的数组对象,例如Number对于 N extends Number .

对于泛型类型参数,我们需要跟踪哪些子类类型参数与原始泛型类型参数匹配,通过类层次结构向下,直到我们到达原始 Class ,其中我们报告具有任何边界的泛型类型参数,或者我们达到实际的 Class对象,我们在其中报告类。

这是一个基于您的类(class)的程序,它可以报告您想要的信息。

它必须创建一个 StackClass es,从原始类到声明该字段的类。然后弹出类,沿着类层次结构向下走。它在当前类中找到与前一类的类型参数匹配的类型参数,记下任何类型参数名称更改和当前类提供的新类型参数的新位置。例如。 T变成 N extends NumberThing出发时至 NumberThing .当类型参数是实际类时,循环迭代停止,例如Integer ,或者如果我们已经到达原始类,在这种情况下我们报告类型参数名称和任何边界,例如N extends Number .

我还包括了几个额外的类,SuperclassSubclass , 其中Subclass反转在 Superclass 中声明的泛型类型参数的顺序, 以提供额外的测试。我还包括了SpecificIntegerThing (非通用),作为测试用例,以便迭代停止在 IntegerThing , 举报 Integer , 在到达 SpecificIntegerThing 之前在堆栈中。

// Just to have some bounds to report.
import java.io.Serializable;
import java.util.RandomAccess;

// Needed for the implementation.
import java.lang.reflect.*;
import java.util.Arrays;
import java.util.Stack;

public class ExtractArguments {

public static class Thing<T> {
public T thing;
}

public static class NumberThing<N extends Number> extends Thing<N> {}

public static class IntegerThing extends NumberThing<Integer> {}

public static class SpecificIntegerThing extends IntegerThing {}

public static class Superclass<A extends Serializable, B> {
public A thing;
}

// A and B are reversed in the extends clause!
public static class Subclass<A, B extends RandomAccess & Serializable>
extends Superclass<B, A> {}

public static void main(String[] args)
{
for (Class<?> clazz : Arrays.asList(
Thing.class, NumberThing.class,
IntegerThing.class, SpecificIntegerThing.class,
Superclass.class, Subclass.class))
{
try
{
Field field = clazz.getField("thing");
System.out.println("Field " + field.getName() + " of class " + clazz.getName() + " is: " +
getFieldTypeInformation(clazz, field));
}
catch (NoSuchFieldException e)
{
System.out.println("Field \"thing\" is not found in class " + clazz.getName() + "!");
}
}
}

getFieldTypeInformation方法处理堆栈。

   private static String getFieldTypeInformation(Class<?> clazz, Field field)
{
Type genericType = field.getGenericType();
// Declared as actual type name...
if (genericType instanceof Class)
{
Class<?> genericTypeClass = (Class<?>) genericType;
return genericTypeClass.getName();
}
// .. or as a generic type?
else if (genericType instanceof TypeVariable)
{
TypeVariable<?> typeVariable = (TypeVariable<?>) genericType;
Class<?> declaringClass = field.getDeclaringClass();
//System.out.println(declaringClass.getName() + "." + typeVariable.getName());

// Create a Stack of classes going from clazz up to, but not including, the declaring class.
Stack<Class<?>> stack = new Stack<Class<?>>();
Class<?> currClass = clazz;
while (!currClass.equals(declaringClass))
{
stack.push(currClass);
currClass = currClass.getSuperclass();
}
// Get the original type parameter from the declaring class.
int typeVariableIndex = -1;
String typeVariableName = typeVariable.getName();
TypeVariable<?>[] currTypeParameters = currClass.getTypeParameters();
for (int i = 0; i < currTypeParameters.length; i++)
{
TypeVariable<?> currTypeVariable = currTypeParameters[i];
if (currTypeVariable.getName().equals(typeVariableName))
{
typeVariableIndex = i;
break;
}
}

if (typeVariableIndex == -1)
{
throw new RuntimeException("Expected Type variable \"" + typeVariable.getName() +
"\" in class " + clazz + "; but it was not found.");
}

// If the type parameter is from the same class, don't bother walking down
// a non-existent hierarchy.
if (declaringClass.equals(clazz))
{
return getTypeVariableString(typeVariable);
}

// Pop them in order, keeping track of which index is the type variable.
while (!stack.isEmpty())
{
currClass = stack.pop();
// Must be ParameterizedType, not Class, because type arguments must be
// supplied to the generic superclass.
ParameterizedType superclassParameterizedType = (ParameterizedType) currClass.getGenericSuperclass();
Type currType = superclassParameterizedType.getActualTypeArguments()[typeVariableIndex];
if (currType instanceof Class)
{
// Type argument is an actual Class, e.g. "extends ArrayList<Integer>".
currClass = (Class) currType;
return currClass.getName();
}
else if (currType instanceof TypeVariable)
{
TypeVariable<?> currTypeVariable = (TypeVariable<?>) currType;
typeVariableName = currTypeVariable.getName();
// Reached passed-in class (bottom of hierarchy)? Report it.
if (currClass.equals(clazz))
{
return getTypeVariableString(currTypeVariable);
}
// Not at bottom? Find the type parameter to set up for next loop.
else
{
typeVariableIndex = -1;
currTypeParameters = currClass.getTypeParameters();
for (int i = 0; i < currTypeParameters.length; i++)
{
currTypeVariable = currTypeParameters[i];
if (currTypeVariable.getName().equals(typeVariableName))
{
typeVariableIndex = i;
break;
}
}

if (typeVariableIndex == -1)
{
// Shouldn't get here.
throw new RuntimeException("Expected Type variable \"" + typeVariable.getName() +
"\" in class " + currClass.getName() + "; but it was not found.");
}
}
}
}
}
// Shouldn't get here.
throw new RuntimeException("Missed the original class somehow!");
}

getTypeVariableString方法有助于生成类型参数名称和任何边界。

   // Helper method to print a generic type parameter and its bounds.
private static String getTypeVariableString(TypeVariable<?> typeVariable)
{
StringBuilder buf = new StringBuilder();
buf.append(typeVariable.getName());
Type[] bounds = typeVariable.getBounds();
boolean first = true;
// Don't report explicit "extends Object"
if (bounds.length == 1 && bounds[0].equals(Object.class))
{
return buf.toString();
}
for (Type bound : bounds)
{
if (first)
{
buf.append(" extends ");
first = false;
}
else
{
buf.append(" & ");
}
if (bound instanceof Class)
{
Class<?> boundClass = (Class) bound;
buf.append(boundClass.getName());
}
else if (bound instanceof TypeVariable)
{
TypeVariable<?> typeVariableBound = (TypeVariable<?>) bound;
buf.append(typeVariableBound.getName());
}
}
return buf.toString();
}
}

这是输出:

Field thing of class ExtractArguments$Thing is: T
Field thing of class ExtractArguments$NumberThing is: N extends java.lang.Number
Field thing of class ExtractArguments$IntegerThing is: java.lang.Integer
Field thing of class ExtractArguments$SpecificIntegerThing is: java.lang.Integer
Field thing of class ExtractArguments$Superclass is: A extends java.io.Serializable
Field thing of class ExtractArguments$Subclass is: B extends java.util.RandomAccess & java.io.Serializable

关于java - 如何为 Java 类字段生成准确的泛型表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28143029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com