java反射

个人觉得java反射的意义在于setAccessible,这样可以读到,修改private属性的东西。又感觉破坏了原有的封装特点。不知道对不对,欢迎指正。

 

package com.annotation;



import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;



public class NameDemo {

    

    public static void main(String[] args) throws Exception {

        Class clazz = Class.forName("com.annotation.Name");

        Constructor con = clazz.getConstructor(new Class[]{

                String.class, String.class

        });

        Name christy = (Name) con.newInstance("Christy","Guo");

        System.out.println(christy.getFirstName() + " " + christy.getLastName());

        

        Field[] fields = clazz.getDeclaredFields();

        for(int i = 0 ; i <fields.length; i ++){

            System.out.println(fields[i].getName() + " Accessible: " + fields[i].isAccessible());

        }

        

        Method[] methods = clazz.getMethods();

        for(int i = 0 ; i <methods.length; i ++){

            System.out.println(methods[i].getName()+ " Accessible: " + methods[i].isAccessible());

        }

        

        

        Field field = clazz.getDeclaredField("firstName");

        if(!field.isAccessible()){

            field.setAccessible(true);

            field.set(christy, "Ruth");

        }

        

        Method method = clazz.getDeclaredMethod("setLastName", new Class[]{String.class});

        method.invoke(christy, "Guoo");

        

        System.out.println(christy.getFirstName() + " " + christy.getLastName());

    }



}

 

你可能感兴趣的:(java反射)