简体   繁体   中英

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.

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?

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).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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