Java:通过泛型类型的反射调用特定方法
如何在泛型类型上调用特定方法?我想调用 getter/setter 方法。
编辑:例如:
class BurningSun<T>
{
public void kitchenSink()
{
Class c = Class.forName(/*What to put here for <T> ?*/)
/*
Reflections code
*/
}
}
嗯,那么在各种框架中如何调用和设置 bean 的 getter 方法呢?
How can I invoke a particular method on a generic type? I want to invoke a a 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在泛型类型内部,如果没有人告诉您,则无法在运行时获取类型参数的名称。
在运行时,
BurningSun
和BurningSun
是完全等效的,您甚至可以将一个转换为另一个(尽管这不是类型安全的)。因此,通常如果您确实需要泛型对象中的类型参数的类对象,您可以让别人在构造函数中将其提供给您。
(您需要在这里捕获或声明一些异常。)
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>
andBurningSun<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.
(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.