Java examples for Reflection:Method Name
Return the mutator method for attribute with specified name and type.
//package com.java2s; 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 = "java2s.com"; Class attributeType = String.class; boolean mustBePublic = true; System.out.println(getMutator(type, name, attributeType, mustBePublic));/* w w w. j a v a 2 s . co m*/ } /** 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."; throw new OpenDataException(message); } return mutator; } catch (final NoSuchMethodException nsme) { final String message = "Missing mutator for field " + name; throw new OpenDataException(message); } } }