import java.lang.reflect.*;
import java.io.*;
class ReflectPointTest
{
public static void main(String[] args) throws Exception
{
//System.out.println("Hello World!");
//Constructor需要导入java.lang.reflect.*这个包,获取构造方法
Constructor constructor=ReflectPoint.class.getConstructor(int.class,int.class);
//新建对象并赋值
ReflectPoint reflectpoint=(ReflectPoint)constructor.newInstance();
System.out.println(reflectpoint);
//获取x字段值
Field fieldX=reflectpoint.getClass().getField("x");
//打印x的值
System.out.println(fieldX.get(reflectpoint));
//获取y字段的值
Field fieldY=reflectpoint.getClass().getDeclaredField("y");
//打印y的值
fieldY.setAccessible(true);
System.out.println(fieldY.get(reflectpoint));
}
}
class ReflectPoint
{
public int x;
public int y;
ReflectPoint(int x,int y)
{
this.x=x;
this.y=y;
}
}
疑问:明明参数为两个参数为int的构造函数,为何运行时出错?
|
|