- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试在运行时推理泛型。有几个很棒的库可以做到这一点(例如 gentyref、ClassMate 和 Guava)。然而,它们的用法有点让我难以理解。
具体来说,我想提取一个与子类上下文中的特定字段匹配的表达式。
这是一个使用 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)的程序,它可以报告您想要的信息。
它必须创建一个 Stack
的 Class
es,从原始类到声明该字段的类。然后弹出类,沿着类层次结构向下走。它在当前类中找到与前一类的类型参数匹配的类型参数,记下任何类型参数名称更改和当前类提供的新类型参数的新位置。例如。 T
变成 N extends Number
从Thing
出发时至 NumberThing
.当类型参数是实际类时,循环迭代停止,例如Integer
,或者如果我们已经到达原始类,在这种情况下我们报告类型参数名称和任何边界,例如N extends Number
.
我还包括了几个额外的类,Superclass
和 Subclass
, 其中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/
当然,您可以将剩余文件大小除以当前下载速度,但如果您的下载速度波动(而且它会波动),这不会产生很好的结果。有什么更好的算法可以产生更平滑的倒计时? 最佳答案 安exponential moving a
对于一个业余项目,我正在尝试对齐照片并创建 3D 图片。我基本上在一个钻机上有 2 个相机,我用来拍照。我会自动尝试以您获得 3D SBS 图像的方式对齐图像。 它们是高分辨率图像,这意味着需要处理大
当然,您可以将剩余的文件大小除以当前的下载速度,但如果您的下载速度波动(而且会波动),这不会产生很好的结果。什么是产生更平滑倒计时的更好算法? 最佳答案 安exponential moving ave
我有一个数据集,其中包含患有糖尿病和未患有糖尿病的人。我想使用这些数据训练一个模型来计算糖尿病状况未知的人的风险概率。我知道在培训中没有被诊断出糖尿病的人大多数都没有糖尿病,但很可能其中一些人可能患有
let parent = path[row-1] let child = path[row] let indexOfChild = matrix[parent.obje
我正在编写一些使用 Element.getBoundingClientRect 的代码(gBCR),加上内联样式更新,以执行计算。 这不适用于一般网站,我不关心或不感兴趣是否有“更好的 CSS 方式”
我有一个很大的 csv 文件,其中包含大量脏数据,我想通过消除所有不是绝对必要的值来稍微清理一下它。 Here是我正在谈论的文件。 它有以下组件: 网站,标题,开始日期,开始日期,雇主,地点,纬度,
有谁知道一个库,它为 Java 提供了一个错误不高于 1-2 毫秒的 Thread.sleep()? 我尝试了 sleep 、错误测量和 BusyWait 的混合,但在不同的 Windows 机器上我
UiApp有DateBox和 DateTimeFormat 对于那个类(class)。但是,不存在诸如 TimePicker 或 TimeBox 这样的东西,用户可以通过明确指定的方式(例如通过使用
因此,我使用 sklearn 的 svm.SVC 模块编写了一个程序来学习 mnist 数据集,出于某种原因,每当我计算其准确性为 100% 时。这似乎好得令人难以置信,这是预期的吗? from sk
我当前找到了 gpytorch ( https://github.com/cornellius-gp/gpytorch )。它似乎是将 GPR 集成到 pytorch 中的一个很棒的包。第一次测试也呈
我正在使用 QT Creator 5.9 创建一个简单的 Web 浏览器模型,我的 EditLine/Text Box 有问题: 1.如何在转到不同的网站/页面后自动更新显示的 URL 字符串。 2。
我在 Linux 上尝试 time -p 命令,我写了一些代码来浪费 CPU 周期: #include using namespace std; int main() { long int c;
亲爱的程序员/脚本编写者/工程师/其他人, 问题:我目前正在为 Android 3.2 平板电脑开发增强现实应用程序,但在获取准确的罗盘读数方面遇到一些问题。我需要确切地知道平板电脑所面向的 (z)
我最近一直在尝试了解 Apache Spark 作为 Scikit Learn 的替代品,但在我看来,即使在简单的情况下,Scikit 收敛到准确模型的速度也远远快于 Spark。例如,我使用以下脚本
如果不是,它的准确性如何? 我想在下载之前知道图片的大小。 最佳答案 HTTP Content-length header 是否格式错误?是的。 您是否应该相信它能公平地表示消息正文的大小?是的。 关
这是一个关于 ngram 线性回归的问题,使用 Tf-IDF(术语频率 - 逆文档频率)。为此,我使用 numpy 稀疏矩阵和 sklearn 进行线性回归。 使用一元语法时,我有 53 个案例和 6
对于某些给定的固定宽度,如何计算特定标签 (NSTextField) 中字符串的高度? 我用谷歌搜索了各种方法并尝试了 this method from Apple .它的工作原理,除了高度变成一行对
我是一名优秀的程序员,十分优秀!