carlspring
carlspring

Reputation: 32627

How do you instantiate a java.lang.reflect.Method?

My method accepts a Method object as a parameter. Therefore, I need to create a mock up instance of a java.lang.reflect.Method. It turns out the class is final and has no public constructor. Okay. So... Is there some factory I need to use or what...? The java.lang.reflect.ReflectAccess class is package scoped and it appears to be the sort of factory I'm looking for (except for the fact I can't use it). What's the deal here...?

Yeah, I could always get an instance of some Class and pick a random Method, but I suppose there's a much more sensible way...?

Thanks in advance!

Upvotes: 6

Views: 4010

Answers (3)

AlexR
AlexR

Reputation: 115368

Try to use reflection.

Constructor c = Method.class.getDeclaredConstructor(Class.class, String.class, Class[].class, Class.class, Class[].class, int.class, int.class, String.class, byte[].class, byte[].class, byte[].class);
c.setAccessible(true);
c.newInstance(....); // send correct arguments

This should work.

Upvotes: 5

MByD
MByD

Reputation: 137382

Method is always related to a class (or instance), so what's the use of getting a method not from its class?

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1501586

Yeah, I could always get an instance of some Class and pick a random Method, but I suppose there's a much more sensible way...?

No, that is the sensible way. Nothing else makes sense. What would it even mean to have a method which isn't part of a class? What would happen when you invoked it?

If this is for testing, I suggest you create a class with an appropriate method in it specifically for this purpose.

Upvotes: 4

Related Questions