导包进去还是报错
- package cn.itcast.day1;
- import java.lang.reflect.Constructor;
- public class ReflectTest {
-
- public static void main(String[] args) {
- 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);
- System.out.println(int[].class.isPrimitive());
- System.out.println(int[].class.isArray());
-
- //new String(new StringBuffer("abc"));
- Constructor constructor1 = String.class.getConstructor(StringBuffer.class);
- String str2 = (String)constructor1.newInstance(new StringBuffer("abc"));
- System.out.println(str2.charAt(2));
-
- ReflectPoint pt1 = new ReflectPoint(3,5);
- Field fieldY = pt1.getClass().getField("y");
- //fieldY的值是多少?是5,错!fieldY不是对象身上的变量,而是类上,要用它对应的值
- System.out.println(fieldY.get(pt1));
- Field fieldX = pt1.getClass().getDeclaredField("x");
- fieldX.setAccessible(true);
- System.out.println(fieldX.get(pt1));
-
-
- //changeStringValue(pt1);
- //System.out.println(pt1);
- }
-
- /*private static void changeStringValue(Object obj){
- Field[] fields = obj.getClass().getFields();
- for(Field field : fields){
- //
- if(field.getType()== String.class){
- String oldValue = (String)field.get(obj);
- String newValue = oldValue.replace('b','a');
- field.set(obj, newValue);
- }
- }
- }
- */
- }
复制代码 |