gpt4 book ai didi

java - 使用反射调用具有通用参数的方法

转载 作者:行者123 更新时间:2023-12-02 05:19:27 25 4
gpt4 key购买 nike

我试图将两个已知类型的泛型(accumulationFunctionresultBindings)传递到下面的反射调用例程中,但我遇到了麻烦。有人可以帮助我了解如何实现这一目标吗?

package com.amir.method.compiler;

//hidden imports

import java.util.Set;

public class CompiledReferencedAttributeMethod implements CompiledMethod {

final Class<?> generatedClazz;
//how do i pass the arguments below into the invoke routine??
final KnownWorkData<AccumulationFunction> accumulationFunction;
final KnownWorkData<Set<Executable<InstanceSetValue>>> resultBindings;

public CompiledReferencedAttributeMethod(final int hash,
final KnownWorkData<AccumulationFunction> accumulationFunction,
final KnownWorkData<Set<Executable<InstanceSetValue>>> resultBindings) {
this.generatedClazz = ReferencedAttributeMethodGenerator.get().compileMethod(
"com.amir.hotspot.GeneratedGRAMethod" +hash, "dynamicGra", accumulationFunction, resultBindings);
this.accumulationFunction = accumulationFunction;
this.resultBindings = resultBindings;
}

@Override
public WorkDataValue invokeCompiled(final Instance onInst,
final ExecutionParms parm,
final WorkDataDefinition returntype,
final TaskContext context) {
try {
return (WorkDataValue) this.generatedClazz
.getMethod("dynamicGra",
Instance.class,
ExecutionParms.class,
WorkDataDefinition.class,
TaskContext.class)
.invoke(null, onInst, parm, returntype, this.accumulationFunction, this.resultBindings, context);
} catch(Exception e) {
throw new ExecuteCompiledMethodException(this.toString(), e);
}
}

}

最佳答案

由于您无法使用泛型和不同参数重载方法(请参阅: Oracle’s tutorial “Restrictions on Generics” ),因此您不必担心反射 API 的泛型。

没有歧义,你可以简单地得到你的方法:

Method m = this.generatedClazz.getMethod("dynamicGra",
Instance.class,
ExecutionParms.class,
WorkDataDefinition.class,
KnownWorkData.class,
KnownWorkData.class,
TaskContext.class);

然后您使用 null 进行调用,因此这意味着dynamicGra 必须是静态的,如果不是这种情况,您必须传递要调用该方法的 generatedClazz 实例:

Object instance = this.generatedClazz.newInstance(); // A new one or any other reference of generatedClazz
m.invoke(instance, onInst, parm, returntype, this.accumulationFunction, this.resultBindings, context);

关于java - 使用反射调用具有通用参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26613588/

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