Java面试

Java反射

2017-11-29  本文已影响9人  草帽小子J

学习反射首先就了解下它的作用吧,这样在编码的时候才会知道何时会用到反射。

能干啥

Java反射机制就是在编译时并不确定是哪个类被加载了,而是在程序运行的时候才加载;它允许程序运行的时期进行自我检查和对内部的成员进行操作。

实现

几个反射机制的类

java.lang.Class
java.lang.

应用

package Reflect;
class Test{
    //ToDo...
}
 
class TjunTest{
    public static void main(String[] args) {
         Class<?>  test1 = null;
         Class<?>  test2 = null;
         Class<?>  test3 = null;
         try{
            test1 = Class.forName("Reflect.Test");
        }catch(Exception e){
            e.printStackTrace();
        }
        test2=new Test().getClass();
        test3=Test.class;
         
        System.out.println(test1.getName());//Reflect.Test
        System.out.println(test2.getName());//Reflect.Test
        System.out.println(test3.getName());//Reflect.Test
    }
}

总结下获取类的方法:

  1. Class test1 = Class.forName("Reflect.Test");
  2. Class test2 = new Test().getClass();
  3. Class test3 = Test.class;
package Reflect;
 
class Student{
    private String name;
    private int age;

    public Student() {
         
    }
    public Student(int age){
        this.age=age;
    }
    public Student(String name, int age) {
        this.age=age;
        this.name=name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString(){
        return this.name+"  "+this.age;
    }
}
 
class Test1{
    public static void main(String[] args) {
        Class<?> test1=null;
        try{
            test1=Class.forName("Reflect.Student");
        }catch (Exception e) {
            e.printStackTrace();
        }
        Student stu=null;
        Student stu1=null;
        Student stu2=null;
        Student stu3=null;
       //获取所有构造方法
       Constructor<?> cons[]=test1.getConstructors();
        try {
            stu  =(Student) test1.newInstance();//注意Student构造函数的参数
            stu1=(Student) cons[0].newInstance();
            stu2=(Student) cons[1].newInstance(5);
            stu3=(Student) cons[2].newInstance("t",6);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        stu.setName("tjun");
        stu.setAge(22);
        System.out.println(stu.toString());//tjun 22
        System.out.println(stu1.toString());//null 0
        System.out.println(stu2.toString());//null 5
        System.out.println(stu3.toString());//t 6
    }
} 

总结实例化的方式:

  1. Test test1=Class.forName("Reflect.Student");
    Student stu=(Student) test1.newInstance()
  2. 获取全部构造方法,按选择实例化:
    Constructor<?> cons[]=test1.getConstructors();//获取全部构造函数
    stu1=(Student) cons[0].newInstance();//注意构造方法的参数

公用类

interface Person{
    public static final String name="asw";
    public static  int age=22;
    public void foot();
    public void run(String name, int age);
} 

class Student implements Person{
    private String score;
    public Student() {
         
    }
    public Student(String score){
        this.score=score;
    }
    public String getScore() {
        return score;
    }
    public void setSex(String score) {
        this.score = score;
    }
    @Override
    public void foot(){
        System.out.println(nam+" ");
    }
    @Override
    public void run(String name, int age){
        System.out.println(name+"  "+age);
    }
}

获取属性

class Test {
    public static void main(String[] args) {
        Class<?> test = null;
        try {
            test = Class.forName("Reflect.Student");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("本类属性");
        Field[] field = test.getDeclaredFields();  // 取得本类的全部属性
        for (int i = 0; i < field.length; i++) {
            // 权限修饰符
            int mo = field[i].getModifiers();
            String priv = Modifier.toString(mo);
            // 属性类型
            Class<?> type = field[i].getType();
            System.out.println(priv + " " + type.getName() + " "
                    + field[i].getName() + ";");
        }
        System.out.println("实现的接口或者父类的属性");
        // 取得实现的接口或者父类的属性
        Field[] filed1 = test.getFields();
        for (int j = 0; j < filed1.length; j++) {
            // 权限修饰符
            int mo = filed1[j].getModifiers();
            String priv = Modifier.toString(mo);
            // 属性类型
            Class<?> type = filed1[j].getType();
            System.out.println(priv + " " + type.getName() + " "
                    + filed1[j].getName() + ";");
        }
    }
}

总结获取属性:

  1. Field[] field = test.getDeclaredFields();//获取本类全部属性
  2. Field[] filed1 = test.getFields();//获取父类或者接口的属性
  3. int mo = filed[i].getModifiers(); String priv = Modifier.toString(mo);//获取具体的权限修饰符
  4. Class<?> type = filed[i].getType();//获取属性类型
  5. Class<?> intes[]=test.getInterfaces();//获取所有的实现的接口
  6. Constructor<?> cons[]=test.getConstructors();//获取全部构造函数
  7. Class<?> temp=demo.getSuperclass(); //获取父类
class Test {
    public static void main(String[] args) {
        Class<?> test = null;
        Object obj = null;
        try {
            test = Class.forName("Reflect.Student");
            obj = test.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try{
            //调用Student类中的foot方法
            Method method=test.getMethod("foot");
            method.invoke(test.newInstance());
            //调用Student的run方法
            method=test.getMethod("run", String.class,int.class);
            method.invoke(test.newInstance(),"tjun",22);
             
        }catch (Exception e) {
            e.printStackTrace();
        }
       setter(obj,"Score","男",String.class);
       getter(obj,"Score");
    }
   /**
     * @param obj
     *            操作的对象
     * @param att
     *            操作的属性
     * */
    public static void getter(Object obj, String att) {
        try {
            Method method = test.getMethod("get" + att);
            System.out.println(method.invoke(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * @param obj
     *            操作的对象
     * @param att
     *            操作的属性
     * @param value
     *            设置的值
     * @param type
     *            参数的属性
     * */
    public static void setter(Object obj, String att, Object value,
            Class<?> type) {
        try {
            Method method = test.getMethod("set" + att, type);
            method.invoke(obj, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//操作属性
class Test1 {
    public static void main(String[] args) throws Exception {
        Class<?> test = null;
        Object obj = null;
 
        test = Class.forName("Reflect.Student");
        obj = test.newInstance();
 
        Field field = test.getDeclaredField("score");
        field.setAccessible(true);//打破封装性
        field.set(obj, "100");
        System.out.println(field.get(obj));
    }
}

总结:

  1. 调用方法:
    method=test.getMethod("run", String.class,int.class);//获得指定方法
    method.invoke(test.newInstance(),"tjun",22);//调用
  2. 操作属性:
    Field field = test.getDeclaredField("score");//获得指定属性
    field.setAccessible(true);//打破封装性
    field.set(obj, "100");//操作属性值
上一篇下一篇

猜你喜欢

热点阅读