可以的,参数类型是没有限制的。通过以下代码可以证明。
接口:
public interface MyInterface {void print()
}
实现类:
public class MyInterfaceImpl implements MyInterface {@Override
public void print() {
System.out.println("interfaceImpl")
}
}
import java.lang.reflect.Methodpublic class Test {
public static void main(String[] args) throws Exception {
Test instance = Test.class.newInstance()
Method method = Test.class.getDeclaredMethod("test", MyInterface.class)
MyInterface myInterface = new MyInterfaceImpl()
method.invoke(instance, myInterface)
}
public void test(MyInterface myInterface) {
myInterface.print()
}
}
ava反射调用可变参数的方法的方式是传入objects参数,如下代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Reflect {
public static void main(String[] args) throws Exception {
Class<?>clazz = Single.class
Single single = (Single) clazz.newInstance()
List<String>list = new ArrayList<String>(){
private static final long serialVersionUID = 1L
{
add("fuck")
add("ni")
add("mei")
}
}
//获取method两种方式, 在method中 数组的的空间大小是可以随便写的不一定使用0
/* 1 */
Method method = clazz.getDeclaredMethod("method", Array.newInstance(Object.class, 0).getClass())
/* 2 */
method = clazz.getDeclaredMethod("method", (new Object[0]).getClass())
//初始化参数