Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 662
carlspring Avatar asked Feb 20 '23 13:02

carlspring


2 Answers

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.

like image 62
AlexR Avatar answered Mar 02 '23 18:03

AlexR


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.

like image 21
Jon Skeet Avatar answered Mar 02 '23 16:03

Jon Skeet