简体   繁体   English

method.getClass()。newInstance()和SomeClass.class.newInstance()之间的区别?

[英]Difference between method.getClass().newInstance() and SomeClass.class.newInstance()?

Recently I started messing around with reflection a little. 最近,我开始有点反省。 I encountered an issue that I can't find any answer to. 我遇到一个找不到任何答案的问题。 I'll try to explain as best as I can what the issue is. 我将尽力解释问题的根源。

Firstly I have a method that I got from reflection that has an annotation. 首先,我有一个从反射中获得的方法,该方法具有注释。 When I try to invoke this method I need an instance of the class it's in ofcourse. 当我尝试调用此方法时,我当然需要该类的一个实例。 This is what I did because it would be the easiest to do in my project: 这是我所做的,因为这在我的项目中最容易做到:

method.invoke(method.getClass().newInstance(), context);

However, this did not work. 但是,这没有用。 The exception thrown with this method is NoSuchMethodException . 用此方法引发的异常是NoSuchMethodException But when I tried to just get the class named someClass that contains the method directly it did not throw an exception and returned the method succesfully: 但是,当我尝试获取名为someClass的类直接包含该方法时,它没有引发异常并成功返回了该方法:

method.invoke(someClass.class.newInstance(), context);

I hope someone more experienced could clearify this so I could learn from this and hopefully use reflection with more ease in the future. 我希望有经验的人可以澄清这一点,以便我可以从中学到东西,并希望将来可以更轻松地使用反射。

Thanks in advance 提前致谢

-DutchJelly -DutchJelly

method.getClass() returns Method.class , the class object for Method . Method.class method.getClass()返回Method.class ,它是Method的类对象。 This is just like how eg "ABC".getClass() returns String.class . 这就像"ABC".getClass()返回String.class

What you are probably looking for is method.getDeclaringClass() . 您可能正在寻找的是method.getDeclaringClass()

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

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