`
pangxin12345
  • 浏览: 186888 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java反射笔记

    博客分类:
  • java
阅读更多

package com.tjpu.helen.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

import com.sun.java_cup.internal.internal_error;

public class TestReflect {

    public static void main(String[] args) throws Exception{
        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());
        //int是基本类型
        System.out.println(int.class.isPrimitive());
        //true
        System.out.println(int.class==Integer.TYPE);
        //false
        System.out.println(int.class==Integer.class);
       
        //int数组不是基本类型
        System.out.println(int[].class.isPrimitive());
        //int数组时数组
        System.out.println(int[].class.isArray());
        //int是基本类型
        System.out.println(int.class.isPrimitive());
       
        System.out.println("------------------------------------");
        //获得方法是需要类型
        Constructor constructor1=String.class.getConstructor(StringBuffer.class);
        String str2=(String)constructor1.newInstance(new StringBuffer("abc"));
        System.out.println(str2);
       
        String str3=(String)Class.forName("java.lang.String").newInstance();
       
        ReflectPoint ref1=new ReflectPoint(3,5);
        //仅仅代码字节码字段
        Field fieldy=ref1.getClass().getField("y");
        //他不知道是哪个对象的y,fieldy
        System.out.println(fieldy.get(ref1));
        //暴力反射  只要用于对私有成员变量
        Field fieldx=ref1.getClass().getDeclaredField("x");
        fieldx.setAccessible(true);
        System.out.println(fieldx.get(ref1));
        //利用反射循环改变字段值
        Field[] fields=ref1.getClass().getFields();
        for(Field field:fields){
            if(field.getType()==String.class){
                String oldValue=(String)field.get(ref1);
                String newValue=oldValue.replace("b", "a");
                field.set(ref1,newValue);
            }
        }
        System.out.println(ref1.str1);
        System.out.println(ref1.str2);
        System.out.println(ref1.str3);
       
    }
}

 

 

package com.tjpu.helen.test;

public class ReflectPoint {
    private int x;
    public int y;
    public String str1="abcdb";
    public String str2="basktball";
    public String str3="itcast";
    public ReflectPoint(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }
   
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics