根据Propertydescriptor判断属性是否有getsetg方法

一:根据Propertydescriptor判断属性是否有get和setg方法

 根据Propertydescriptor判断属性是否有get和setg方法,Java.beans包下

package com.hdx.hkafka;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;

public class PropertydescriptorTest {

    private String testName;

    public static void main(String[] args) {
        Class<?> clazz = PropertydescriptorTest.class;
        try {
            // 如果属性testName没有get和set方法此行抛出异常 Method not found: isTestName
            PropertyDescriptor propertydescriptor = new PropertyDescriptor("testName", clazz);

            // 获取个get方法
            propertydescriptor.getReadMethod();
            // 获取个set方法
            propertydescriptor.getWriteMethod();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
    }
}

 二:获取get和set方法并执行

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class PropertydescriptorTest {

    public String getTestName() {
        return testName;
    }

    public void setTestName(String testName) {
        this.testName = testName;
    }

    private String testName = "大明星";

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        Class<?> clazz = PropertydescriptorTest.class;
        Object bean = clazz.newInstance();
        try {
            // 如果属性testName没有get和set方法此行抛出异常2
            PropertyDescriptor propertydescriptor = new PropertyDescriptor("testName", bean.getClass());

            // 获取个get方法
            Method readMethod = propertydescriptor.getReadMethod();
            Object val = readMethod.invoke(bean);
            System.out.println("val:"+val);

            // 获取个set方法
            Method writeMethod = propertydescriptor.getWriteMethod();
            writeMethod.invoke(bean, "设置名称");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

posted @ 2022-12-04 22:27  银河系的极光  阅读(249)  评论(0)    收藏  举报