- package strengthenTest;
- public class ReflectPoint {
- private int x;
- public int y;
-
- public ReflectPoint(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
-
- }
复制代码- package strengthenTest;
- import java.lang.reflect.Constructor;
- import java.text.DateFormat.Field;
- public class ReflectTest {
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- String str1 = "abc";
- Class cls1 = str1.getClass();
- Class cls2 = String.class;
- Class cls3 = Class.forName("java.lang.String");
- System.out.println(cls1 == cls2);
- System.out.println(cls1 == cls3);
-
- System.out.println(cls1.isPrimitive());
- System.out.println(int.class.isPrimitive());
- System.out.println(int.class == Integer.class);
- System.out.println(int.class == Integer.TYPE);
- //数组类型的class实例对象用的是.isArray()
- System.out.println(int[].class.isPrimitive());
- System.out.println(int[].class.isArray());
- //总之,只要是在源程序中出现的类型,都有各自的class实例对象,例如int[], void
- //可以调用isPrimitive和isArray方法知道是什么样的类型
-
-
- //可以传进来若干个class类型也可以传进来一个数组进来 jdk1.5新特性可变参数
- String.class.getConstructor(StringBuffer.class);
-
- Constructor constructor1 = String.class.getConstructor(StringBuffer.class);
- String str2 = (String)constructor1.newInstance(new StringBuffer("abc"));
- //编译期不知道是(String)
- System.out.println(str2.charAt(2));
- //程序开发分编译期和运行期,错误出在哪个阶段
- ReflectPoint pt1 = new ReflectPoint(3,5);
- Field fieldY = pt1.getClass().getField("y");
- System.out.println(fieldY.get(pt1));
-
- }
- }
复制代码
|
|