我是靠谱客的博主 激昂夕阳,这篇文章主要介绍JAVA反射调用,现在分享给大家,希望可以做个参考。

这是将要用来反射的类TestRef,接下来将完成以下几个反射
1.反射调用方法test();
2.反射调用标识为private的方法getString(String args);
3.反射成员变量List s;

需要被反射的类如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class TestRef { public List<String> s; public List<String> getS() { return s; } public void setS(List<String> s) { this.s = s; } public void test(String[] args){ System.out.println(Arrays.toString(args)); } @SuppressWarnings("unused") private String getString(String args){ return args; } }

反射的实现如下:

复制代码
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
public static void main(String[] args) { TestRef t = new TestRef(); try { //通过TestRef的实例对象t 得到TestRef的Class的实例化对象 Class c1 = t.getClass(); //另外两种得到Class的方法 //Class c2 = Class.forName("testCase3.TestRef"); //Class c3 = TestRef.class; //获取TestRef自定义的全部方法 for (Method m : c1.getDeclaredMethods()) { if ("test".equals(m.getName())) { //以invoke方法反射调用,传入值如下: m.invoke(t, new Object[] { new String[] { "12312312", "asdfsd", "yufhjdfhgj" } }); } //通过setS方法给TestRef的List<String> s赋值 if ("setS".equals(m.getName())) { List<String> l = new ArrayList<String>(); l.add("1234"); l.add("56723dd"); m.invoke(t, new Object[] { l }); System.out.println("ListS为:" + t.getS()); } if ("getString".equals(m.getName())) { //私有方法必须setAccessible(true),不然是没有权限访问的 m.setAccessible(true); String str = (String) m.invoke(t, "getString123"); System.out.println("反射getString方法返回:" + str); } } } catch (Exception e) { e.printStackTrace(); } }

反射List li ,单拿出来,此处将绕过泛型的检测

复制代码
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
@Test public void test() { //泛型为Inteegr List<Integer> li = new ArrayList<Integer>(); Class c2 = li.getClass(); try { //通过invoke方法,将List的add方法反射调用,我们可以存非Integer对象 //具体操作如下: Method m = c2.getMethod("add", Object.class); m.invoke(li, 1); m.invoke(li, (Object) 2.0); m.invoke(li, (Object) "nmkl"); m.invoke(li, new Object[] { "sadas" }); m.invoke(li, new Object[] { "123fdgd" }); m.invoke(li, new Object[] { 12.0 }); m.invoke(li, new Object[] { new String[] { "ahjk", "qwyui", "16783ugi" } }); System.out.println(li); for (int i = 0; i < li.size(); i++) { System.out.println(li.get(i)); //取出List<Integer>中通过反射存的String[] Object o = li.get(i); if (o instanceof String[]) { System.out.println(Arrays.toString((String[]) o)); } } } catch (Exception e) { e.printStackTrace(); } }

最后

以上就是激昂夕阳最近收集整理的关于JAVA反射调用的全部内容,更多相关JAVA反射调用内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部