List of usage examples for java.lang.reflect Method getName
@Override
public String getName()
From source file:jp.go.nict.langrid.p2pgridbasis.data.langrid.converter.ConvertUtil.java
static public DataAttributes encode(Object data) throws DataConvertException { setLangridConverter();//from w w w . j a v a2 s.c om logger.debug("##### encode #####"); try { DataAttributes attr = new DataAttributes(); for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(data)) { if (PropertyUtils.isReadable(data, descriptor.getName())) { if (descriptor.getName().equalsIgnoreCase("supportedLanguages")) { //supportedLanguages attr.setAttribute(descriptor.getName(), (String) converter.lookup(descriptor.getPropertyType()).convert(String.class, PropertyUtils.getProperty(data, descriptor.getName()))); continue; } else if (descriptor.getName().equalsIgnoreCase("instance")) { // // continue; } else if (descriptor.getName().equalsIgnoreCase("wsdl")) { // // continue; } else if (descriptor.getName().equalsIgnoreCase("interfaceDefinitions")) { // // ServiceType type = (ServiceType) data; Map<String, ServiceInterfaceDefinition> map = new HashMap<String, ServiceInterfaceDefinition>(); map = type.getInterfaceDefinitions(); String str = ""; try { for (ServiceInterfaceDefinition s : map.values()) { str = str + "ProtocolId=" + s.getProtocolId() + "\n"; str = str + "Definition=" + Base64.encode(StreamUtil.readAsBytes(s.getDefinition().getBinaryStream())) + "\n"; str = str + "###ServiceInterfaceDefinition###\n"; } } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } attr.setAttribute("interfaceDefinition_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("allowedAppProvision")) { Service s = (Service) data; String value = ""; for (String str : s.getAllowedAppProvision()) { value = value + str + "\n"; } attr.setAttribute("allowedAppProvision", value); continue; } else if (descriptor.getName().equalsIgnoreCase("allowedUse")) { Service s = (Service) data; String value = ""; for (String str : s.getAllowedUse()) { value = value + str + "\n"; } attr.setAttribute("allowedUse", value); continue; } else if (descriptor.getName().equalsIgnoreCase("supportedDomains")) { Grid g = (Grid) data; List<Domain> list = g.getSupportedDomains(); String value = ""; for (Domain d : list) { value = value + d.getDomainId() + "\n"; } attr.setAttribute("supportedDomain_list", value); continue; } else if (descriptor.getName().equalsIgnoreCase("partnerServiceNamespaceURIs")) { //partnerServiceNamespaceURIs BPELService s = (BPELService) data; List<String> list = s.getPartnerServiceNamespaceURIs(); String value = ""; for (String str : list) { value = value + str + "\n"; } attr.setAttribute("partnerServiceNamespaceURI_list", value); continue; } else if (descriptor.getName().equalsIgnoreCase("serviceDeployments")) { //ServiceDeployment Service s = (Service) data; String str = ""; for (ServiceDeployment sd : s.getServiceDeployments()) { str = str + "GridId=" + sd.getGridId() + "\n"; str = str + "ServiceId=" + sd.getServiceId() + "\n"; str = str + "NodeId=" + sd.getNodeId() + "\n"; str = str + "ServicePath=" + sd.getServicePath() + "\n"; str = str + "Enabled=" + String.valueOf(sd.isEnabled()) + "\n"; str = str + "CreateTime=" + String.valueOf(sd.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "UpdateTime=" + String.valueOf(sd.getUpdatedDateTime().getTimeInMillis()) + "\n"; if (sd.getDisabledByErrorDate() != null) { str = str + "ErrorDate=" + String.valueOf(sd.getDisabledByErrorDate().getTimeInMillis()) + "\n"; } if (sd.getDeployedDateTime() != null) { str = str + "DeployedTime=" + String.valueOf(sd.getDeployedDateTime().getTimeInMillis()) + "\n"; } str = str + "###ServiceDeployment###\n"; } attr.setAttribute("deployment_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("serviceEndpoints")) { //ServiceEndpoint StringBuilder str = new StringBuilder(); Service s = (Service) data; for (ServiceEndpoint se : s.getServiceEndpoints()) { str.append("GridId=" + se.getGridId() + "\n"); str.append("ProtocolId=" + se.getProtocolId() + "\n"); str.append("ServiceId=" + se.getServiceId() + "\n"); str.append("Enabled=" + String.valueOf(se.isEnabled()) + "\n"); str.append("Url=" + se.getUrl().toString() + "\n"); str.append("AuthUserName=" + se.getAuthUserName() + "\n"); str.append("AuthPassword=" + se.getAuthPassword() + "\n"); str.append("DisableReason=" + se.getDisableReason() + "\n"); str.append("CreateTime=" + String.valueOf(se.getCreatedDateTime().getTimeInMillis()) + "\n"); str.append("UpdateTime=" + String.valueOf(se.getUpdatedDateTime().getTimeInMillis()) + "\n"); if (se.getDisabledByErrorDate() != null) { str.append("ErrorDate=" + String.valueOf(se.getDisabledByErrorDate().getTimeInMillis()) + "\n"); } str.append("###ServiceEndpoint###\n"); } attr.setAttribute("endpoint_list", str.toString()); continue; } else if (descriptor.getName().equalsIgnoreCase("invocations")) { //Invocation String str = ""; Service s = (Service) data; for (Invocation in : s.getInvocations()) { str = str + "InvocationName=" + in.getInvocationName() + "\n"; str = str + "OwnerServiceGridId=" + in.getOwnerServiceGridId() + "\n"; str = str + "OwnerServiceId=" + in.getOwnerServiceId() + "\n"; str = str + "ServiceGridId=" + in.getServiceGridId() + "\n"; str = str + "ServiceId=" + in.getServiceId() + "\n"; str = str + "ServiceName=" + in.getServiceName() + "\n"; str = str + "CreateTime=" + String.valueOf(in.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "UpdateTime=" + String.valueOf(in.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Invocation###\n"; } attr.setAttribute("invocations_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("metaAttributes")) { //metaAttributes String str = ""; if (data.getClass().getName().endsWith("ResourceType")) { ResourceType r = (ResourceType) data; for (ResourceMetaAttribute a : r.getMetaAttributes().values()) { str = str + "DomainId=" + a.getDomainId() + "\n"; str = str + "AttributeId=" + a.getAttributeId() + "\n"; str = str + "###MetaAttribute###\n"; } } else if (data.getClass().getName().endsWith("ServiceType")) { ServiceType s = (ServiceType) data; for (ServiceMetaAttribute a : s.getMetaAttributes().values()) { str = str + "DomainId=" + a.getDomainId() + "\n"; str = str + "AttributeId=" + a.getAttributeId() + "\n"; str = str + "###MetaAttribute###\n"; } } else { logger.info("metaAttributes : " + data.getClass().getName()); } attr.setAttribute("metaAttribute_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("attributes")) { //attribute String str = ""; if (data.getClass().getName().endsWith("User")) { User u = (User) data; for (UserAttribute a : u.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getUserId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Service")) { Service s = (Service) data; for (ServiceAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getServiceId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Node")) { Node s = (Node) data; for (NodeAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getNodeId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Grid")) { Grid s = (Grid) data; for (GridAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Resource")) { Resource s = (Resource) data; for (ResourceAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getResourceId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } attr.setAttribute("attribute_list", str); continue; } else if (data instanceof Service && (descriptor.getName().equals("alternateServiceId") || descriptor.getName().equals("useAlternateServices"))) { // // continue; } //Read OK if (data instanceof BPELService && descriptor.getName().equals("transferExecution")) { // ignore } else { attr.setAttribute(descriptor.getName(), BeanUtils.getProperty(data, descriptor.getName())); } } else if (descriptor.getPropertyType().isArray()) { logger.debug("name : " + descriptor.getName() + " isArray"); // // attr.setAttribute(descriptor.getName(), (String) converter.lookup(descriptor.getPropertyType()) .convert(String.class, PropertyUtils.getProperty(data, descriptor.getName()))); } else { logger.debug("Name : " + descriptor.getName()); for (Method m : data.getClass().getMethods()) { if (m.getName().equalsIgnoreCase("get" + descriptor.getName()) || m.getName().equalsIgnoreCase("is" + descriptor.getName())) { if (m.getParameterTypes().length != 0) { // // logger.debug("class : " + data.getClass().getName()); logger.debug("?:Skip"); break; } else { // // logger.debug("value : " + m.invoke(data)); } attr.setAttribute(descriptor.getName(), m.invoke(data).toString()); break; } } } } return attr; } catch (InvocationTargetException e) { throw new DataConvertException(e); } catch (IllegalArgumentException e) { throw new DataConvertException(e); } catch (IllegalAccessException e) { throw new DataConvertException(e); } catch (NoSuchMethodException e) { throw new DataConvertException(e); } }
From source file:Mopex.java
/** * Returns a String that is formatted as a Java method declaration having * the same header as the specified method but with the code parameter * substituted for the method body.//from ww w . j av a 2s .co m * * @return String * @param m * java.lang.Method * @param code * String */ //start extract createReplacementMethod public static String createReplacementMethod(Method m, String code) { Class[] pta = m.getParameterTypes(); String fpl = formalParametersToString(pta); Class[] eTypes = m.getExceptionTypes(); String result = m.getName() + "(" + fpl + ")\n"; if (eTypes.length != 0) result += " throws " + classArrayToString(eTypes) + "\n"; result += "{\n" + code + "}\n"; return result; }
From source file:ReflectUtil.java
/** * <p>Attempts to find an accessible version of the method passed in, where accessible * is defined as the method itself being public and the declaring class being public. * Mostly useful as a workaround to the situation when * {@link PropertyDescriptor#getReadMethod()} and/or * {@link java.beans.PropertyDescriptor#getWriteMethod()} returns methods that are not * accessible (usually due to public implementations of interface methods in private * classes).</p>/*ww w . j av a 2 s. c o m*/ * * <p>Checks the method passed in and if it already meets these criteria it is returned * immediately. In general this leads to very little performance overhead</p> * * <p>If the method does not meet the criteria then the class' interfaces are scanned * for a matching method. If one is not found, then the class' superclass hierarchy * is searched. Finally, if no matching method can be found the original method is * returned.</p> * * @param m a method that may or may not be accessible * @return either an accessible version of the same method, or the method passed in if * an accessible version cannot be found */ public static Method findAccessibleMethod(final Method m) { // If the passed in method is accessible, then just give it back. if (isPublic(m.getModifiers()) && isPublic(m.getDeclaringClass().getModifiers())) return m; if (m.isAccessible()) return m; final Class<?> clazz = m.getDeclaringClass(); final String name = m.getName(); final Class<?>[] ptypes = m.getParameterTypes(); // Else, loop through the interfaces for the declaring class, looking for a // public version of the method that we can call for (Class<?> iface : clazz.getInterfaces()) { try { Method m2 = iface.getMethod(name, ptypes); if (m2.isAccessible()) return m2; if (isPublic(iface.getModifiers()) && isPublic(m2.getModifiers())) return m2; } catch (NoSuchMethodException nsme) { /* Not Unexpected. */ } } // Else loop through the superclasses looking for a public method Class<?> c = clazz.getSuperclass(); while (c != null) { try { Method m2 = c.getMethod(name, ptypes); if (m2.isAccessible()) return m2; if (isPublic(c.getModifiers()) && isPublic(m2.getModifiers())) return m2; } catch (NoSuchMethodException nsme) { /* Not Unexpected. */ } c = c.getSuperclass(); } // If we haven't found anything at this point, just give up! return m; }
From source file:cross.applicationContext.ReflectionApplicationContextGenerator.java
/** * Checks and adds type information for the given method, class and object * to the properties list./* w w w .j a v a2s. co m*/ * * @param method the method to check for a property * @param javaClass the class to check for settable property * @param obj the stub / default object of type javaClass * @param properties the properties list */ public static void checkMutableProperties(Method method, Class<?> javaClass, Object obj, List<ObjectProperty> properties) { if (method.getName().startsWith("get") || method.getName().startsWith("is")) { String methodBaseName = method.getName().startsWith("get") ? method.getName().substring(3) : method.getName().substring(2); try { //check for corresponding setter if (javaClass.getMethod("set" + methodBaseName, method.getReturnType()) != null) { String propertyName = toLowerCaseName(methodBaseName); // System.out.print("Handling property " + propertyName); ObjectProperty p = new ObjectProperty(); Class<?> returnType = method.getReturnType(); if (returnType.isArray()) { p.type = "Array"; } else { p.type = returnType.getCanonicalName(); } Class<?> genericReturnType = getGenericMethodReturnType(method); p.genericType = genericReturnType.getCanonicalName(); p.name = propertyName; Object methodObject = null; try { methodObject = method.invoke(obj); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { log.warn(ex.getLocalizedMessage()); } String value = null; if (methodObject == null) { value = ""; } else { if (methodObject.getClass().isArray()) { value = methodObject.getClass().getComponentType().getCanonicalName(); } else { value = methodObject.toString(); } } if (value == null) { value = ""; } else { value = value.trim(); } if (value.contains("\"")) { //remove the quotes that surround Strings value = value.replaceAll("\"", ""); } else if (value.contains("'")) { //remove the quotes that surround characters value = value.replaceAll("'", ""); } else if (value.endsWith("d") || value.endsWith("D") || value.endsWith("f") || value.endsWith("F") || value.endsWith("l") || value.endsWith("L")) { //remove the "double", "float", or "long" letters if they are there value = value.substring(0, value.length() - 1); } p.value = value; System.out.println(" value: " + p.value + " type: " + p.type); properties.add(p); } } catch (NoSuchMethodException ex) { log.info("Ignoring read-only property {}", methodBaseName); //Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { log.warn(ex.getLocalizedMessage()); } } }
From source file:com.github.drinkjava2.jbeanbox.springsrc.ReflectionUtils.java
/** * Determine whether the given method is a CGLIB 'renamed' method, following the pattern "CGLIB$methodName$0". * /*from w w w. j a v a2s.com*/ * @param renamedMethod * the method to check * @see org.springframework.cglib.proxy.Enhancer#rename */ public static boolean isCglibRenamedMethod(Method renamedMethod) { String name = renamedMethod.getName(); return (name.startsWith(CGLIB_RENAMED_METHOD_PREFIX) && CGLIB_RENAMED_METHOD_PATTERN .matcher(name.substring(CGLIB_RENAMED_METHOD_PREFIX.length())).matches()); }
From source file:com.hurence.logisland.util.kura.Metrics.java
public static <T> T readFrom(final T object, final Map<String, Object> metrics) { Objects.requireNonNull(object); for (final Field field : FieldUtils.getFieldsListWithAnnotation(object.getClass(), Metric.class)) { final Metric m = field.getAnnotation(Metric.class); final boolean optional = field.isAnnotationPresent(Optional.class); final Object value = metrics.get(m.value()); if (value == null && !optional) { throw new IllegalArgumentException( String.format("Field '%s' is missing metric '%s'", field.getName(), m.value())); }/*from w w w .j a v a 2 s . c om*/ if (value == null) { // not set but optional continue; } try { FieldUtils.writeField(field, object, value, true); } catch (final IllegalArgumentException e) { // provide a better message throw new IllegalArgumentException(String.format("Failed to assign '%s' (%s) to field '%s'", value, value.getClass().getName(), field.getName()), e); } catch (final IllegalAccessException e) { throw new RuntimeException(e); } } for (final Method method : MethodUtils.getMethodsListWithAnnotation(object.getClass(), Metric.class)) { final Metric m = method.getAnnotation(Metric.class); final boolean optional = method.isAnnotationPresent(Optional.class); final Object value = metrics.get(m.value()); if (value == null && !optional) { throw new IllegalArgumentException( String.format("Method '%s' is missing metric '%s'", method.getName(), m.value())); } if (value == null) { // not set but optional continue; } try { method.invoke(object, value); } catch (final IllegalArgumentException e) { // provide a better message throw new IllegalArgumentException(String.format("Failed to call '%s' (%s) with method '%s'", value, value.getClass().getName(), method.getName()), e); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } return object; }
From source file:net.jodah.typetools.TypeResolver.java
/** * Populates the {@code map} with variable/argument pairs for the {@code functionalInterface}. *//*from w ww. j a va 2 s. c o m*/ private static void populateLambdaArgs(Class<?> functionalInterface, final Class<?> lambdaType, Map<TypeVariable<?>, Type> map) { if (GET_CONSTANT_POOL != null) { try { // Find SAM for (Method m : functionalInterface.getMethods()) { if (!m.isDefault() && !Modifier.isStatic(m.getModifiers()) && !m.isBridge()) { // Skip methods that override Object.class Method objectMethod = OBJECT_METHODS.get(m.getName()); if (objectMethod != null && Arrays.equals(m.getTypeParameters(), objectMethod.getTypeParameters())) continue; // Get functional interface's type params Type returnTypeVar = m.getGenericReturnType(); Type[] paramTypeVars = m.getGenericParameterTypes(); // Get lambda's type arguments ConstantPool constantPool = (ConstantPool) GET_CONSTANT_POOL.invoke(lambdaType); String[] methodRefInfo = constantPool.getMemberRefInfoAt( constantPool.getSize() - resolveMethodRefOffset(constantPool, lambdaType)); // Skip auto boxing methods if (methodRefInfo[1].equals("valueOf") && constantPool.getSize() > 22) { try { methodRefInfo = constantPool.getMemberRefInfoAt(constantPool.getSize() - resolveAutoboxedMethodRefOffset(constantPool, lambdaType)); } catch (MethodRefOffsetResolutionFailed ignore) { } } if (returnTypeVar instanceof TypeVariable) { Class<?> returnType = TypeDescriptor.getReturnType(methodRefInfo[2]) .getType(lambdaType.getClassLoader()); if (!returnType.equals(Void.class)) map.put((TypeVariable<?>) returnTypeVar, returnType); } TypeDescriptor[] arguments = TypeDescriptor.getArgumentTypes(methodRefInfo[2]); // Handle arbitrary object instance method references int paramOffset = 0; if (paramTypeVars[0] instanceof TypeVariable && paramTypeVars.length == arguments.length + 1) { Class<?> instanceType = TypeDescriptor.getObjectType(methodRefInfo[0]) .getType(lambdaType.getClassLoader()); map.put((TypeVariable<?>) paramTypeVars[0], instanceType); paramOffset = 1; } // Handle local final variables from context that are passed as arguments. int argOffset = 0; if (paramTypeVars.length < arguments.length) { argOffset = arguments.length - paramTypeVars.length; } for (int i = 0; i + argOffset < arguments.length; i++) { if (paramTypeVars[i] instanceof TypeVariable) { map.put((TypeVariable<?>) paramTypeVars[i + paramOffset], arguments[i + argOffset].getType(lambdaType.getClassLoader())); } } break; } } } catch (Exception ignore) { } } }
From source file:com.sitewhere.web.rest.documentation.RestDocumentationGenerator.java
/** * Generate documentation for a documented method. * /* ww w . j a v a 2 s .c om*/ * @param baseUri * @param method * @return * @throws SiteWhereException */ protected static ParsedMethod parseMethod(String baseUri, Method method, File resources) throws SiteWhereException { ParsedMethod parsed = new ParsedMethod(); parsed.setName(method.getName()); parsed.setBaseUri(baseUri); ApiOperation op = method.getAnnotation(ApiOperation.class); if (op == null) { throw new SiteWhereException( "Spring ApiOperation annotation missing on documented method: " + method.getName()); } parsed.setSummary(op.value()); RequestMapping mapping = method.getAnnotation(RequestMapping.class); if (mapping == null) { throw new SiteWhereException( "Spring RequestMapping annotation missing on documented method: " + method.getName()); } // Find URI mapping. String[] mappings = mapping.value(); parsed.setRelativeUri("/"); if (mappings.length > 0) { parsed.setRelativeUri(mappings[0]); } // Find request method. RequestMethod[] methods = mapping.method(); if (methods.length == 0) { throw new SiteWhereException("No request methods configured."); } parsed.setRequestMethod(methods[0]); Documented documented = method.getAnnotation(Documented.class); String markdownFilename = documented.description(); if (markdownFilename.length() == 0) { markdownFilename = method.getName() + ".md"; } // Parse method-level markdown description. File markdownFile = new File(resources, markdownFilename); if (!markdownFile.exists()) { throw new SiteWhereException("Method markdown file missing: " + markdownFile.getAbsolutePath()); } PegDownProcessor processor = new PegDownProcessor(); String markdown = readFile(markdownFile); parsed.setDescription(processor.markdownToHtml(markdown)); // Parse parameters. List<ParsedParameter> params = parseParameters(method); Collections.sort(params, new Comparator<ParsedParameter>() { @Override public int compare(ParsedParameter o1, ParsedParameter o2) { return o1.getName().compareTo(o2.getName()); } }); parsed.setParameters(params); parseExamples(method, parsed, resources); return parsed; }
From source file:edu.cornell.mannlib.vedit.util.FormUtils.java
/** * Populates form objects with bean values *//*from w w w.ja v a 2s . com*/ public static void populateFormFromBean(Object bean, String action, EditProcessObject epo, FormObject foo, Map<String, String> BadValuesHash) { Class beanClass = (epo != null && epo.getBeanClass() != null) ? epo.getBeanClass() : bean.getClass(); Method[] meths = beanClass.getMethods(); for (int i = 0; i < meths.length; i++) { if (meths[i].getName().indexOf("set") == 0) { // we have a setter method Method currMeth = meths[i]; Class[] currMethParamTypes = currMeth.getParameterTypes(); Class currMethType = currMethParamTypes[0]; if (SUPPORTED_TYPE_LIST.contains(currMethType)) { //we only want people directly to type in ints, strings, and dates //of course, most of the ints are probably foreign keys anyway... String elementName = currMeth.getName().substring(3, currMeth.getName().length()); //see if there's something in the bean using //the related getter method Class[] paramClass = new Class[1]; paramClass[0] = currMethType; try { Method getter = beanClass.getMethod("get" + elementName, (Class[]) null); Object existingData = null; try { existingData = getter.invoke(bean, (Object[]) null); } catch (Exception e) { log.error("Exception invoking getter method"); } String value = ""; if (existingData != null) { if (existingData instanceof String) { value += existingData; } else if (!(existingData instanceof Integer && (Integer) existingData < 0)) { value += existingData.toString(); } } String badValue = (String) BadValuesHash.get(elementName); if (badValue != null) { value = badValue; } foo.getValues().put(elementName, value); } catch (NoSuchMethodException e) { //ignore it } } } } }
From source file:org.thoughtland.xlocation.Util.java
public static Method getMethod(Class<?> clazz, String name, Object[] args) { Util.log(null, Log.DEBUG, "Looking for " + name); for (Method m : clazz.getDeclaredMethods()) { Util.log(null, Log.DEBUG, "Got method " + clazz.getSimpleName() + "." + m.getName() + "( " + TextUtils.join(", ", m.getParameterTypes()) + " )"); if (m.getName().equals(name)) { Util.log(null, Log.DEBUG, " names match!"); if (args == null) return m; Class<?>[] params = m.getParameterTypes(); if (params.length == args.length) { Util.log(null, Log.DEBUG, " params length match!"); boolean matches = true; for (int i = 0; i < params.length; i++) { if (args[i] != null && !params[i].isInstance(args[i])) { Util.log(null, Log.DEBUG, " param[" + i + "] " + args[i].getClass().getName() + " does not match type " + params[i].getSimpleName()); matches = false; break; }//w ww .ja va 2 s. c om } if (matches) { Util.log(null, Log.DEBUG, "Found match for " + name); return m; } } } } return null; }