java反射调用方法可以传非基本类型吗?如对象、接口

Python012

java反射调用方法可以传非基本类型吗?如对象、接口,第1张

可以的,参数类型是没有限制的。通过以下代码可以证明。

接口:

public interface MyInterface {

    void print()

}

实现类:

public class MyInterfaceImpl implements MyInterface {

    @Override

    public void print() {

        System.out.println("interfaceImpl")

    }

}

通过反射调用方法

import java.lang.reflect.Method

public 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())

//初始化参数