集册 Java实例教程 返回具有指定名称和类型的属性的mutator方法。

返回具有指定名称和类型的属性的mutator方法。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

623
返回具有指定名称和类型的属性的mutator方法。
/** 来 自 时 代 J     a    v  a - nowjava.com**/

//package com.nowjava;

import java.lang.reflect.Method;


import javax.management.openmbean.OpenDataException;


public class Main {

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

        Class type = String.class;

        String name = "nowjava.com";

        Class attributeType = String.class;

        boolean mustBePublic = true;

        System.out.println(getMutator(type, name, attributeType,

                mustBePublic));

    }
/**来自 nowjava - 时代Java**/

    /** Prefix for all mutator methods. */

    private static final String MUTATOR_PREFIX = "set";


    /**

     * Return the mutator method for attribute with specified name and type.

     *

     * @param type the type to retrieve method from.

     * @param name the name of the attribute.

     * @param attributeType the attribute attributeType.

     * @return the mutator method if any.

     * @throws OpenDataException if unable to find mutator method.

     */

    public static Method getMutator(final Class type, final String name,

            final Class attributeType, final boolean mustBePublic)

            throws OpenDataException {

        try {

            final String accessorName = MUTATOR_PREFIX

                    + Character.toUpperCase(name.charAt(0))

                    + name.substring(1);

            final Class[] params = new Class[] { attributeType };

            final Method mutator;

            if (mustBePublic) {

                mutator = type.getMethod(accessorName, params);

            } else {

                mutator = type.getDeclaredMethod(accessorName, params);

            }

            if (Void.TYPE != mutator.getGenericReturnType()) {

                final String message = "Mutator for " + name

                        + " should not return any value.";

                
展开阅读全文