本帖最后由 funneies 于 2013-8-19 14:18 编辑
想遍历一下构造方法,但是使用forName方式得到的Class对象运行时,会跳过foreach遍历,没有结果显示,想知道为什么?- package day06.enhance;
- public class ReflectPoint {
- private int x;
- public int y;
- public String str1 = "ball";
- public String str2 = "basketball";
- public String str3 = "itcast";
- public ReflectPoint(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
- @Override
- public String toString(){
- return "str1:"+str1+"str2:"+str2+"str3:"+str3;
- }
- }
- package day06.enhance;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- public class ReflectTest {
- public static void main(String []args) throws Exception{
- Class clazz = Class.forName("day06.enhance.ReflectPoint").getClass();
- Class clazz1 = ReflectPoint.class;
- ReflectPoint pt1 = new ReflectPoint(3,5);
- Class clazz2 = pt1.getClass();
- Constructor[] constructors = clazz2.getConstructors();//此处使用clazz时,没有显示,使用clazz2时显示正常。
- Constructor constructor = Class.forName("java.lang.String").getConstructor(StringBuffer.class);
- String str = (String)constructor.newInstance(new StringBuffer("abc"));
- System.out.println(str.charAt(2));
- for (Constructor constructor2 : constructors) {
- System.out.println(constructor2);
- }
- }
- }
复制代码 运行结果:
c
public day06.enhance.ReflectPoint(int,int)
|