>  기사  >  Java  >  Java 자체 검사 메커니즘을 구현하는 방법

Java 자체 검사 메커니즘을 구현하는 방법

WBOY
WBOY앞으로
2023-04-24 08:04:061547검색

    Concept

    JavaBean

    실제 프로그래밍에서는 Student, Employee, Order와 같은 값 개체를 래핑하기 위해 일부 클래스가 필요한 경우가 종종 있습니다. 객체는 캡슐화되며 다음과 같은 특성을 갖습니다.

    • 속성은 모두 비공개입니다.

    • 매개 변수가 없는 공개 생성자 메서드가 있습니다.

    • 개인 속성에 대한 공개 getXxx 메서드와 setXxx 메서드를 제공합니다.

    예를 들어 속성 ​​이름이 name인 경우 getName 메서드는 속성 이름 값을 반환하고 setName 메서드는 이름 값을 설정합니다. 일반적으로 메서드 이름은 get 또는 set에 속성을 더한 값입니다. 이름, 속성 이름의 첫 글자는 대문자로 표시됩니다. getter/setter라고 하는 메서드에는 반환 값이 있어야 하며, setter 값에는 반환 값이 없고 메서드 매개 변수가 있어야 합니다. 예를 들어, 다음 예는 다음과 같습니다.

    Java 자체 검사 메커니즘을 구현하는 방법 이러한 특성을 충족하는 클래스를 JavaBeans라고 합니다.

    Introspection

    Introspection(Inspector) 메커니즘은 리플렉션을 기반으로 하며 Bean 클래스 속성에 대한 Java 언어의 기본 처리 방법입니다. 이벤트.

    클래스에 getXXX 메소드나 setXXX 메소드 또는 getXXX와 setXXX 메소드가 모두 있는 한, getXXX 메소드에는 메소드 매개변수가 없고 반환 값이 있습니다. setXXX 메소드에는 반환 값이 없으며 메소드 매개변수가 있습니다. ; 그러면 자체 검사 메커니즘은 XXX를 속성으로 간주합니다.

    예를 들어 다음 코드

    에서는 age 속성이 Employee 클래스에 전혀 선언되지 않고 해당 getter 및 setter만 선언됩니다. be an attribute

    package com.shixun.introspector;
    
    public class Employee {
        private String name;
        private Double score;
    
        // age将被内省认为是属性
        public int getAge(){
            return 30;
        }
    
        // name将被内省认为是属性
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        // score将被内省认为是属性
        public Double getScore() {
            return score;
        }
    
        public void setScore(Double score) {
            this.score = score;
        }
    
        public static void main(String[] args) {
            
    
        }
    }

    관련 API

    Java 내부 검사 관련 주요 클래스와 인터페이스는 다음과 같습니다.

      java.beans.Introspector 클래스: JavaBean 속성, 이벤트 및 일반적으로 getBeanInfo 메소드를 사용하여 BeanInfo 객체를 반환합니다.
    • Java.beans.BeanInfo 인터페이스: 이 유형의 객체는 일반적으로 Introspector 클래스를 통해 반환됩니다. 반환 속성 설명자 개체(PropertyDescriptor), 메서드 설명자 개체(MethodDescriptor), bean 설명자(BeanDescriptor) 개체의 메서드를 제공합니다. java.beans.Introspector类: 为获得JavaBean属性、事件、方法提供了标准方法;通常使用其中的getBeanInfo方法返回BeanInfo对象;

    • Java.beans.BeanInfo接口:不能直接实例化,通常通过Introspector类返回该类型对象,提供了返回属性描述符对象(PropertyDescriptor)、方法描述符对象(MethodDescriptor) 、 bean描述符(BeanDescriptor)对象的方法;

    • Java.beans.PropertyDescriptor类

    Java.beans.PropertyDescriptor 클래스: 속성을 설명하는 데 사용됩니다.

    PropertyDescriptor 클래스 메서드를 사용하여 속성 관련 정보를 얻을 수 있습니다. 예를 들어 getName 메서드는 속성 이름을 반환합니다. PropertyDescriptor 클래스는 getter를 얻을 수 있는 메서드를 정의합니다. 및 속성의 setter 메소드methodMethod 설명Method getReadMethod() 속성에 해당하는 getter 메소드 객체를 반환합니다.Method getWriteMethod()세터 메서드를 반환합니다.

    코드를 사용해 자세히 살펴보겠습니다.

    코드 케이스: 속성 관련 정보 가져오기

    Employee 위 코드와 같이 계속해서 테스트를 위한 주요 함수를 작성합니다

    First BeanInfo 인터페이스를 사용하여 BeanInfo 객체를 얻은 다음 BeanInfo 객체를 통해 PropertyDescriptor 속성 설명을 얻습니다

     //获取BeanInfo的对象
     BeanInfo employeeBeanInfo = Introspector.getBeanInfo(Employee.class);
     //通过BeanInfo对象获取PropertyDescriptor属性描述
     PropertyDescriptor[] propertyDescriptors = employeeBeanInfo.getPropertyDescriptors();
     System.out.println("通过Inspector内省机制获取JavaBean属性======= 打印所有信息 ====================");
     Arrays.stream(propertyDescriptors).forEach(f->{
         System.out.println("====================================");
         System.out.println("属性名:"+f.getName());
         System.out.println("类型:"+f.getPropertyType());
         System.out.println("get方法:"+f.getReadMethod());
         System.out.println("set方法:"+f.getWriteMethod());
     });
    
    // 或者用增强for
    System.out.println("通过Inspector内省机制获取JavaBean属性======= 打印所有信息 ====================");
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
    	System.out.println("====================================");
        System.out.println("名字:" + propertyDescriptor.getName());
        System.out.println("类型:" + propertyDescriptor.getPropertyType());
        System.out.println("get方法:" + propertyDescriptor.getReadMethod());
        System.out.println("set方法:" + propertyDescriptor.getWriteMethod());
    }
    Java 자체 검사 메커니즘을 구현하는 방법실행 결과는 다음과 같습니다.

    여기에서 얻은 get 또는 set 메서드는 리플렉션을 통해 호출됩니다.

    //创建Employee的对象
    Class<?> clazz = Class.forName("com.shixun.introspector.Employee");
    Object employee = clazz.newInstance();
    
    //遍历属性描述对象
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        //打印属性名称
        System.out.println(propertyDescriptor.getName());
        //判断属性名称是不是name
        if (propertyDescriptor.getName().equals("name")) {
            //setter方法
            Method writeMethod = propertyDescriptor.getWriteMethod();
            //调用setName方法
            writeMethod.invoke(employee, "jack");
            //getter方法
            Method readMethod = propertyDescriptor.getReadMethod();
            //调用getName方法
            Object nameValue = readMethod.invoke(employee);
            System.out.println("name属性的值为:" + nameValue);
        }
        //判断属性名称是否为score
        if (propertyDescriptor.getName().equals("score")) {
            //setter方法
            Method scoreWriteMethod = propertyDescriptor.getWriteMethod();
            //调用setScore方法
            scoreWriteMethod.invoke(employee, new Double(3000));
            //getter方法
            Method scoreReadMethod = propertyDescriptor.getReadMethod();
            Object scoreValue = scoreReadMethod.invoke(employee);
            System.out.println("score属性的值为:" + scoreValue);
        }
    }
    System.out.println("当前对象的信息:"+employee.toString());
    Java 자체 검사 메커니즘을 구현하는 방법실행 결과는 다음과 같습니다.

    모든 코드는 하단에 첨부되어 있습니다! ! ! ! ! !

    • 자체 검사 속성에 대한 참고 사항

    • 많은 프레임워크는 검사 메커니즘을 사용하여 객체의 속성을 검색할 때 속성 이름을 정의할 때 이름을 stuName보다 두 개 이상의 소문자로 시작하는 것이 가장 좋습니다. sName을 사용하면 경우에 따라 속성 검색에 실패할 수 있습니다.

    내부 검사 메커니즘은 속성을 검색할 때 선언된 멤버 변수 이름이 아닌 getter 및 setter 메서드를 기반으로 속성 이름을 확인합니다. 수업 중

    🎜🎜 완전한 코드 🎜
    package com.shixun.introspector;
    
    import java.beans.BeanInfo;
    import java.beans.IntrospectionException;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.Arrays;
    
    public class Employee {
        private String name;
        private Double score;
    
        // age将被内省认为是属性
        public int getAge() {
            return 30;
        }
    
        // name将被内省认为是属性
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        // score将被内省认为是属性
        public Double getScore() {
            return score;
        }
    
        public void setScore(Double score) {
            this.score = score;
        }
    
        @Override
        public String toString() {
            return "Employee{" +
                    "name=&#39;" + name + &#39;\&#39;&#39; +
                    ", score=" + score +
                    &#39;}&#39;;
        }
    
        public static void main(String[] args) throws ClassNotFoundException, IntrospectionException, IllegalAccessException, InstantiationException, InvocationTargetException {
            //获取BeanInfo的对象
            BeanInfo employeeBeanInfo = Introspector.getBeanInfo(Employee.class);
    
            //通过BeanInfo对象获取PropertyDescriptor属性描述
            PropertyDescriptor[] propertyDescriptors = employeeBeanInfo.getPropertyDescriptors();
    //        System.out.println("通过Inspector内省机制获取JavaBean属性======= 打印所有信息 ====================");
    //        Arrays.stream(propertyDescriptors).forEach(f->{
    //            System.out.println("====================================");
    //            System.out.println("属性名:"+f.getName());
    //            System.out.println("类型:"+f.getPropertyType());
    //            System.out.println("get方法:"+f.getReadMethod());
    //            System.out.println("set方法:"+f.getWriteMethod());
    //        });
    //
    //
    //
    //        System.out.println("通过Inspector内省机制获取JavaBean属性======= 打印所有信息 ====================");
    //
    //        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
    //            System.out.println("名字:" + propertyDescriptor.getName());
    //            System.out.println("类型:" + propertyDescriptor.getPropertyType());
    //            System.out.println("get方法:" + propertyDescriptor.getReadMethod());
    //            System.out.println("set方法:" + propertyDescriptor.getWriteMethod());
    //        }
    
            //创建Employee的对象
            Class<?> clazz = Class.forName("com.shixun.introspector.Employee");
            Object employee = clazz.newInstance();
    
            //遍历属性描述对象
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                //打印属性名称
                System.out.println(propertyDescriptor.getName());
                //判断属性名称是不是name
                if (propertyDescriptor.getName().equals("name")) {
                    //setter方法
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    //调用setName方法
                    writeMethod.invoke(employee, "jack");
                    //getter方法
                    Method readMethod = propertyDescriptor.getReadMethod();
                    //调用getName方法
                    Object nameValue = readMethod.invoke(employee);
                    System.out.println("name属性的值为:" + nameValue);
                }
                //判断属性名称是否为score
                if (propertyDescriptor.getName().equals("score")) {
                    //setter方法
                    Method scoreWriteMethod = propertyDescriptor.getWriteMethod();
                    //调用setScore方法
                    scoreWriteMethod.invoke(employee, new Double(3000));
                    //getter方法
                    Method scoreReadMethod = propertyDescriptor.getReadMethod();
                    Object scoreValue = scoreReadMethod.invoke(employee);
                    System.out.println("score属性的值为:" + scoreValue);
                }
            }
    
            System.out.println("当前对象的信息:"+employee.toString());
        }
    }

    위 내용은 Java 자체 검사 메커니즘을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    성명:
    이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제