简体   繁体   中英

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!

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.

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.

方法总是与一个类(或实例)相关,那么获取一个不是来自它的类的方法有什么用呢?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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