DutchJelly
DutchJelly

Reputation: 196

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

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

Upvotes: 1

Views: 456

Answers (1)

Radiodef
Radiodef

Reputation: 37845

method.getClass() returns Method.class, the class object for Method. This is just like how e.g. "ABC".getClass() returns String.class.

What you are probably looking for is method.getDeclaringClass().

Upvotes: 2

Related Questions