简体   繁体   English

Java:通过对泛型类型的思考来调用特定方法

[英]Java: Invoke a specific method through reflections on a generic type

How can I invoke a particular method on a generic type? 如何在泛型类型上调用特定方法? I want to invoke aa getter/setter method. 我想调用一个getter / setter方法。

Edit: Ex: 编辑:例如:

class BurningSun<T>
{ 
    public void kitchenSink()
    {
        Class c = Class.forName(/*What to put here for <T> ?*/)
                /*
                Reflections code
                */
    }
}

Hmmm, so how are the bean's getter methods invoked and set in various frameworks? 嗯,那么如何在各种框架中调用和设置bean的getter方法呢?

Inside of a generic type there is no way to get the name of the type parameter at runtime if nobody did tell it to you. 如果没有人告诉您,则在泛型类型内部无法在运行时获取类型参数的名称。

On runtime, a BurningSun<String> and BurningSun<Integer> are completely equivalent, and you can even cast one into the other (this is not type safe, though). 在运行时, BurningSun<String>BurningSun<Integer>是完全等效的,您甚至可以将其中一个BurningSun<Integer>转换为另一个(尽管这不是类型安全的)。

So, usually if you really need the class object of the type parameter inside your generic object, you let someone give it to you in the constructor. 因此,通常,如果您确实需要在泛型对象中使用type参数的类对象,则可以让有人在构造函数中将其提供给您。

class BurningSun<T> {


    private Class<T> paramClass;

    public BurningSun(Class<T> pClass) {
        this.paramClass = pClass;
    }

    public void kitchenSink() {
        T t = paramClass.newInstance();
    }
}

(You would need to catch or declare some exceptions here.) (您需要在此处捕获或声明一些例外。)

Well all method invocation based on reflection is at its most simple about shoving Objects into the method, praying it'll work. 好吧,所有基于反射的方法调用最简单的方法就是将对象推入方法,祈求它可以工作。 So cast & keep your fingers crossed. 因此,投射并保持手指交叉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM