List of usage examples for java.lang Class getMethods
@CallerSensitive public Method[] getMethods() throws SecurityException
From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java
/** * @param className//from w w w .j a v a 2 s . c om * @param tableList */ @SuppressWarnings("unchecked") protected void processCascade(final String className, final List<Table> tableList) { //System.out.println(className); try { Class<?> classObj = Class.forName(packageName + "." + className); //Table table = null; //String tableName = null; if (classObj.isAnnotationPresent(javax.persistence.Table.class)) { for (Method method : classObj.getMethods()) { String methodName = method.getName(); if (!methodName.startsWith("get") || method.isAnnotationPresent(javax.persistence.Transient.class)) { continue; } if (method.isAnnotationPresent(javax.persistence.ManyToOne.class)) { if (method.isAnnotationPresent(org.hibernate.annotations.Cascade.class)) { System.out.println("Missing Cascade[" + method.getName() + "]"); missing++; removeCascadeRule(classObj, method); } } } } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DatamodelGenerator.class, ex); ex.printStackTrace(); } }
From source file:com.sitewhere.web.rest.documentation.RestDocumentationGenerator.java
/** * Parse information for a given controller. * // w w w. j a v a 2 s . c o m * @param controller * @param resourcesFolder * @return * @throws SiteWhereException */ protected static ParsedController parseController(Class<?> controller, File resourcesFolder) throws SiteWhereException { ParsedController parsed = new ParsedController(); Api api = controller.getAnnotation(Api.class); if (api == null) { throw new SiteWhereException("Swagger Api annotation missing on documented controller."); } parsed.setResource(api.value()); DocumentedController doc = controller.getAnnotation(DocumentedController.class); parsed.setName(doc.name()); parsed.setGlobal(doc.global()); System.out.println("Processing controller: " + parsed.getName() + " (" + parsed.getResource() + ")"); RequestMapping mapping = controller.getAnnotation(RequestMapping.class); if (mapping == null) { throw new SiteWhereException( "Spring RequestMapping annotation missing on documented controller: " + controller.getName()); } parsed.setBaseUri("/sitewhere/api" + mapping.value()[0]); // Verify controller markdown file. File markdownFile = new File(resourcesFolder, parsed.getResource() + ".md"); if (!markdownFile.exists()) { throw new SiteWhereException("Controller markdown file missing: " + markdownFile.getAbsolutePath()); } // Verify controller resources folder. File resources = new File(resourcesFolder, parsed.getResource()); if (!resources.exists()) { throw new SiteWhereException("Controller markdown folder missing: " + resources.getAbsolutePath()); } try { PegDownProcessor processor = new PegDownProcessor(); String markdown = readFile(markdownFile); parsed.setDescription(processor.markdownToHtml(markdown)); } catch (IOException e) { throw new SiteWhereException("Unable to read markdown from: " + markdownFile.getAbsolutePath(), e); } Method[] methods = controller.getMethods(); for (Method method : methods) { if (method.getAnnotation(Documented.class) != null) { ParsedMethod parsedMethod = parseMethod(parsed.getBaseUri(), method, resources); parsed.getMethods().add(parsedMethod); } } Collections.sort(parsed.getMethods(), new Comparator<ParsedMethod>() { @Override public int compare(ParsedMethod o1, ParsedMethod o2) { return o1.getSummary().compareTo(o2.getSummary()); } }); return parsed; }
From source file:cat.albirar.framework.dynabean.impl.DynaBeanDescriptor.java
/** * Constructor with the type to implement to get the information. * @param factory The factory to work with * @param typeToImplement the {@link Class} type to implement. * @throws IllegalArgumentException If {@code typeToImplement} is null or isn't an interface *///from ww w . j a va 2 s. co m public DynaBeanDescriptor(IDynaBeanImplementationFactory factory, Class<T> typeToImplement) { this(factory); DynaBeanPropertyDescriptor propDesc; StringBuilder stb; String s; if (typeToImplement == null || typeToImplement.isInterface() == false) { if (typeToImplement == null) { logger.error("The type to implement is required"); throw new IllegalArgumentException("The type to implement is required"); } // Only interfaces logger.error("DynaBean can only implement interfaces. '" + typeToImplement.getName() + "' is not an interface"); throw new IllegalArgumentException("DynaBean can only implement interfaces. '" + typeToImplement.getName() + "' is not an interface"); } implementedType = typeToImplement; if (logger.isDebugEnabled()) { logger.debug("Working for implementing the type '".concat(typeToImplement.getName()).concat("'")); } // Prepare the properties list for (Method method : typeToImplement.getMethods()) { if (isPropertyMethod(method.getName()) && isCorrectProperty(method)) { if ((propDesc = getPropertyByMethodName(method.getName())) == null) { // Put them! propDesc = new DynaBeanPropertyDescriptor(); propDesc.propertyName = fromMethodToPropertyName(method.getName()); propDesc.propertyPath = implementedType.getName().concat(".").concat(propDesc.propertyName); if (logger.isDebugEnabled()) { logger.debug("Working on property '".concat(implementedType.getName()).concat(".") .concat(propDesc.getPropertyName())); } if (isGetter(method.getName())) { propDesc.getterMethod = method; } else { propDesc.setterMethod = method; } resolvePropertyComponentType(propDesc); resolvePropertyEditorForProperty(propDesc); resolvePropertyCloneMethod(propDesc); properties.put(propDesc.getPropertyName(), propDesc); } else { if (isGetter(method.getName())) { propDesc.getterMethod = method; } else { propDesc.setterMethod = method; } } } else { if (!isPropertyMethod(method.getName())) { if (logger.isInfoEnabled()) { logger.info(String.format(PATTERN_IGNORING_PROPERTIES, implementedType.getName(), method.getName(), " is not a property method")); } } if (!isCorrectProperty(method)) { if (logger.isWarnEnabled()) { logger.warn(String.format(PATTERN_IGNORING_PROPERTIES, implementedType.getName(), method.getName(), " is an INVALID PROPERTY METHOD")); } } } } // Check that at least one property is found Assert.isTrue(!properties.isEmpty(), "The model '" + implementedType.getName() + "' doesn't defines a valid model, doesn't have any valid property"); // Check value coherence for (DynaBeanPropertyDescriptor property : properties.values()) { // Check type return and set equals if (property.isRW()) { // All two methods should to have the same type Assert.isTrue( property.getterMethod.getReturnType().equals(property.setterMethod.getParameterTypes()[0]), String.format( "The set and get values of the property '%s' at '%s' model ARE DIFFERENTS. This model is invalid", property.propertyName, implementedType.getName())); } } // The descriptor have all the properties // Prepare the string pattern and test annotations stb = new StringBuilder(); stb.append(implementedType.getSimpleName()).append(" ["); s = ""; for (String name : getPropertyNames()) { // Test annotations processAnnotations(properties.get(name)); // Add the property to the 'toString' pattern stb.append(s).append(name).append("=%s"); s = ", "; } // Change the last element (",") by "]" stb.append("]"); patternForToString = stb.toString(); if (logger.isDebugEnabled()) { logger.debug("Pattern string for '".concat(implementedType.getClass().getName()).concat("': ") .concat(patternForToString)); } validDescriptor = true; }
From source file:bammerbom.ultimatecore.bukkit.resources.utils.JsonRepresentedObject.java
/** * Retrieves a {@link Method} instance declared by the specified class with * the specified name and argument types. Java access modifiers are ignored * during this retrieval. No guarantee is made as to whether the field * returned will be an instance or static field. * <p>//www . j a v a 2 s . c o m * A global caching mechanism within this class is used to store method. * Combined with synchronization, this guarantees that no method will be * reflectively looked up twice. * </p> * <p> * If a method is deemed suitable for return, * {@link Method#setAccessible(boolean) setAccessible} will be invoked with * an argument of {@code true} before it is returned. This ensures that * callers do not have to check or worry about Java access modifiers when * dealing with the returned instance. * </p> * <p/> * This method does <em>not</em> search superclasses of the specified type * for methods with the specified signature. Callers wishing this behavior * should use {@link Class#getDeclaredMethod(String, Class...)}. * * @param clazz The class which contains the method to retrieve. * @param name The declared name of the method in the class. * @param args The formal argument types of the method. * @return A method object with the specified name declared by the specified * class. */ public synchronized static Method getMethod(Class<?> clazz, String name, Class<?>... args) { if (!_loadedMethods.containsKey(clazz)) { _loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>()); } Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames = _loadedMethods.get(clazz); if (!loadedMethodNames.containsKey(name)) { loadedMethodNames.put(name, new HashMap<ArrayWrapper<Class<?>>, Method>()); } Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name); ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<>(args); if (loadedSignatures.containsKey(wrappedArg)) { return loadedSignatures.get(wrappedArg); } for (Method m : clazz.getMethods()) { if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes())) { m.setAccessible(true); loadedSignatures.put(wrappedArg, m); return m; } } loadedSignatures.put(wrappedArg, null); return null; }
From source file:com.kugou.limos.config.AbstractInterfaceConfig.java
protected void checkInterfaceAndMethods(Class<?> interfaceClass, List<MethodConfig> methods) { // ??/* www. j a v a2 s .c o m*/ if (interfaceClass == null) { throw new IllegalStateException("interface not allow null!"); } // ?? if (!interfaceClass.isInterface()) { throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!"); } // ?? if (methods != null && methods.size() > 0) { for (MethodConfig methodBean : methods) { String methodName = methodBean.getName(); if (methodName == null || methodName.length() == 0) { throw new IllegalStateException( "<dubbo:method> name attribute is required! Please check: <dubbo:service interface=\"" + interfaceClass.getName() + "\" ... ><dubbo:method name=\"\" ... /></<dubbo:reference>"); } boolean hasMethod = false; for (java.lang.reflect.Method method : interfaceClass.getMethods()) { if (method.getName().equals(methodName)) { hasMethod = true; break; } } if (!hasMethod) { throw new IllegalStateException( "The interface " + interfaceClass.getName() + " not found method " + methodName); } } } }
From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java
/** * @param leftSide//from ww w .j a va 2 s . c o m * @param rightSide * @param mappedByName * @return */ protected String getRightSideForOneToMany(final Class<?> leftSide, final Class<?> rightSide, final String mappedByName) { if (StringUtils.isEmpty(mappedByName)) { throw new RuntimeException("Couldn't find otherside method name missing for [" + rightSide.getSimpleName() + "] mappedByName[" + mappedByName + "]"); } for (Method method : rightSide.getMethods()) { String methodName = method.getName(); // Skip if it is a not a getter if (!methodName.startsWith("get")) { continue; } //System.out.println("Left Class["+leftSide.getSimpleName()+"] Right["+rightSide.getSimpleName()+"] Right Side Method ["+methodName+"] Ret["+method.getReturnType().getSimpleName()+"]"); // Skip if it is a not a ManyToOne if (!method.isAnnotationPresent(javax.persistence.ManyToOne.class)) { continue; } Class<?> retType = method.getReturnType(); boolean isSet = Collection.class.isAssignableFrom(retType); if (isSet) { Class<?> rt = getSetsClassType(rightSide, methodName); if (rt == null) { continue; // probably because of an interface } retType = rt; //System.out.println("Set["+(retType != null ? retType.getSimpleName() : "NULL")+"]"); } // Skip if the Return Types don't match if (leftSide != retType) { continue; } return getFieldNameFromMethod(method); } return null; }
From source file:com.cloudera.impala.catalog.CatalogServiceCatalog.java
/** * Returns a list of Impala Functions, one per compatible "evaluate" method in the UDF * class referred to by the given Java function. This method copies the UDF Jar * referenced by "function" to a temporary file in "LOCAL_LIBRARY_PATH" and loads it * into the jvm. Then we scan all the methods in the class using reflection and extract * those methods and create corresponding Impala functions. Currently Impala supports * only "JAR" files for symbols and also a single Jar containing all the dependent * classes rather than a set of Jar files. *///ww w. j av a2 s .c om public static List<Function> extractFunctions(String db, org.apache.hadoop.hive.metastore.api.Function function) throws ImpalaRuntimeException { List<Function> result = Lists.newArrayList(); List<String> addedSignatures = Lists.newArrayList(); boolean compatible = true; StringBuilder warnMessage = new StringBuilder(); if (function.getFunctionType() != FunctionType.JAVA) { compatible = false; warnMessage.append("Function type: " + function.getFunctionType().name() + " is not supported. Only " + FunctionType.JAVA.name() + " functions " + "are supported."); } if (function.getResourceUrisSize() != 1) { compatible = false; List<String> resourceUris = Lists.newArrayList(); for (ResourceUri resource : function.getResourceUris()) { resourceUris.add(resource.getUri()); } warnMessage.append("Impala does not support multiple Jars for dependencies." + "(" + Joiner.on(",").join(resourceUris) + ") "); } if (function.getResourceUris().get(0).getResourceType() != ResourceType.JAR) { compatible = false; warnMessage.append("Function binary type: " + function.getResourceUris().get(0).getResourceType().name() + " is not supported. Only " + ResourceType.JAR.name() + " type is supported."); } if (!compatible) { LOG.warn("Skipping load of incompatible Java function: " + function.getFunctionName() + ". " + warnMessage.toString()); return result; } String jarUri = function.getResourceUris().get(0).getUri(); Class<?> udfClass = null; try { Path localJarPath = new Path(LOCAL_LIBRARY_PATH, UUID.randomUUID().toString() + ".jar"); if (!FileSystemUtil.copyToLocal(new Path(jarUri), localJarPath)) { String errorMsg = "Error loading Java function: " + db + "." + function.getFunctionName() + ". Couldn't copy " + jarUri + " to local path: " + localJarPath.toString(); LOG.error(errorMsg); throw new ImpalaRuntimeException(errorMsg); } URL[] classLoaderUrls = new URL[] { new URL(localJarPath.toString()) }; URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls); udfClass = urlClassLoader.loadClass(function.getClassName()); // Check if the class is of UDF type. Currently we don't support other functions // TODO: Remove this once we support Java UDAF/UDTF if (FunctionUtils.getUDFClassType(udfClass) != FunctionUtils.UDFClassType.UDF) { LOG.warn("Ignoring load of incompatible Java function: " + function.getFunctionName() + " as " + FunctionUtils.getUDFClassType(udfClass) + " is not a supported type. Only UDFs are supported"); return result; } // Load each method in the UDF class and create the corresponding Impala Function // object. for (Method m : udfClass.getMethods()) { if (!m.getName().equals("evaluate")) continue; Function fn = ScalarFunction.fromHiveFunction(db, function.getFunctionName(), function.getClassName(), m.getParameterTypes(), m.getReturnType(), jarUri); if (fn == null) { LOG.warn("Ignoring incompatible method: " + m.toString() + " during load of " + "Hive UDF:" + function.getFunctionName() + " from " + udfClass); continue; } if (!addedSignatures.contains(fn.signatureString())) { result.add(fn); addedSignatures.add(fn.signatureString()); } } } catch (ClassNotFoundException c) { String errorMsg = "Error loading Java function: " + db + "." + function.getFunctionName() + ". Symbol class " + udfClass + "not found in Jar: " + jarUri; LOG.error(errorMsg); throw new ImpalaRuntimeException(errorMsg, c); } catch (Exception e) { LOG.error("Skipping function load: " + function.getFunctionName(), e); throw new ImpalaRuntimeException("Error extracting functions", e); } return result; }
From source file:com.wcs.base.util.StringUtils.java
public static String toString(Object obj) { if (obj == null) return null; Class objClass = obj.getClass(); if (objClass.getName().startsWith("java.lang")) return obj.toString(); Method[] methods = null;//from ww w. ja v a 2 s .c o m Field[] fields = objClass.getDeclaredFields(); StringBuffer result = new StringBuffer(); if (isSubClassOf(objClass, "Collection")) { result.append(processIterator(((Collection) obj).iterator(), objClass)); } else if (isSubClassOf(objClass, "Map")) { result.append(processMap((Map) obj, objClass)); } else if (isSubClassOf(objClass, "Iterator")) { result.append(processIterator((Iterator) obj, objClass)); } else if (isSubClassOf(objClass, "Enumeration")) { result.append(processEnumeration((Enumeration) obj, objClass)); } else { if (!(objClass.getName().startsWith("java")) && fields.length > 0) { result.append(obj.getClass().getName()).append(":["); for (int i = 0; i < fields.length; i++) { result.append(fields[i].getName()).append(":"); if (fields[i].isAccessible()) { try { result.append(toString(fields[i].get(obj))); } catch (IllegalAccessException iae) { iae.printStackTrace(); } } else { if (methods == null) { methods = objClass.getMethods(); } for (int j = 0; j < methods.length; j++) { if (methods[j].getName().equalsIgnoreCase("get" + fields[i].getName())) { try { result.append(toString(methods[j].invoke(obj, (Object[]) null))); } catch (IllegalAccessException iae) { iae.printStackTrace(); } catch (InvocationTargetException ite) { ite.printStackTrace(); } } } } result.append("; "); } result.append(']'); } else { result.append(obj); return result.toString(); } } return result.toString(); }
From source file:com.xie.javacase.json.JSONObject.java
private void populateInternalMap(Object bean, boolean includeSuperClass) { Class klass = bean.getClass(); /* If klass.getSuperClass is System class then force includeSuperClass to false. */ if (klass.getClassLoader() == null) { includeSuperClass = false;/*from ww w .ja v a 2s . c o m*/ } Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods(); for (int i = 0; i < methods.length; i += 1) { try { Method method = methods[i]; if (Modifier.isPublic(method.getModifiers())) { String name = method.getName(); String key = ""; if (name.startsWith("get")) { key = name.substring(3); } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object result = method.invoke(bean, (Object[]) null); if (result == null) { map.put(key, NULL); } else if (result.getClass().isArray()) { map.put(key, new JSONArray(result, includeSuperClass)); } else if (result instanceof Collection) { // List or Set map.put(key, new JSONArray((Collection) result, includeSuperClass)); } else if (result instanceof Map) { map.put(key, new JSONObject((Map) result, includeSuperClass)); } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper map.put(key, result); } else { if (result.getClass().getPackage().getName().startsWith("java") || result.getClass().getClassLoader() == null) { map.put(key, result.toString()); } else { // User defined Objects map.put(key, new JSONObject(result, includeSuperClass)); } } } } } catch (Exception e) { throw new RuntimeException(e); } } }
From source file:net.lightbody.bmp.proxy.jetty.xml.XmlConfiguration.java
private Object call(Object obj, XmlParser.Node node) throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException { String id = node.getAttribute("id"); Class oClass = nodeClass(node); if (oClass != null) obj = null;/*from w ww . j av a2s .c o m*/ else if (obj != null) oClass = obj.getClass(); if (oClass == null) throw new IllegalArgumentException(node.toString()); int size = 0; int argi = node.size(); for (int i = 0; i < node.size(); i++) { Object o = node.get(i); if (o instanceof String) continue; if (!((XmlParser.Node) o).getTag().equals("Arg")) { argi = i; break; } size++; } Object[] arg = new Object[size]; for (int i = 0, j = 0; j < size; i++) { Object o = node.get(i); if (o instanceof String) continue; arg[j++] = value(obj, (XmlParser.Node) o); } String method = node.getAttribute("name"); if (log.isDebugEnabled()) log.debug("call " + method); // Lets just try all methods for now Method[] methods = oClass.getMethods(); for (int c = 0; methods != null && c < methods.length; c++) { if (!methods[c].getName().equals(method)) continue; if (methods[c].getParameterTypes().length != size) continue; if (Modifier.isStatic(methods[c].getModifiers()) != (obj == null)) continue; if ((obj == null) && methods[c].getDeclaringClass() != oClass) continue; Object n = null; boolean called = false; try { n = methods[c].invoke(obj, arg); called = true; } catch (IllegalAccessException e) { LogSupport.ignore(log, e); } catch (IllegalArgumentException e) { LogSupport.ignore(log, e); } if (called) { if (id != null) _idMap.put(id, n); configure(n, node, argi); return n; } } throw new IllegalStateException("No Method: " + node + " on " + oClass); }