Java反射

来源:互联网 发布:php开发文档怎么写 编辑:程序博客网 时间:2024/04/27 21:43

一、首先Demo

package com.classz.testz;import java.lang.reflect.Method;public class TestClassForName {public static void main(String[] args) throws Exception{Class<?> ttClass = Class.forName("com.classz.testz.TT"); TestClassForName tm = new TestClassForName();Method[] methods = ttClass.getMethods();for(Method th:methods){if(th.getName().equals("kkk")){th.invoke(ttClass.newInstance(),12);}}}}class TT{public TT() {}private String name;public TT(String name) {this.name=name;}    public void kkk(int m){    System.out.print(m);    }}


二、解释

1、使用Class.forName得到对应的类的。

2、使用newInstance()来获取一个类的实列(必须有个无参数的构造函数,否则会报错)。

3、相关方法查看API,本列子列举调用方法。

三、调用带有参数构造函数

package com.classz.testz;import java.lang.reflect.Method;public class TestClassForName {public static void main(String[] args) throws Exception{Class<?> ttClass = Class.forName("com.classz.testz.TT"); TestClassForName tm = new TestClassForName();Method[] methods = ttClass.getMethods();for(Method th:methods){if(th.getName().equals("kkk")){th.invoke(ttClass.getConstructor(String.class).newInstance("123456"),12);}}}}class TT{public TT() {}private String name;public TT(String name) {this.name = name;System.out.println(name);}    public void kkk(int m){    System.out.print(m+"--"+name);    }}


四、解释

1、使用ttClass.getConstructor(String.class)可以制定构造函数。

 

 

原创粉丝点击