List of usage examples for java.lang Class getDeclaredMethods
@CallerSensitive public Method[] getDeclaredMethods() throws SecurityException
From source file:CrossRef.java
/** * Print the fields and methods of one class. *///from w ww . ja v a2 s . c o m protected void doClass(Class c) { int i, mods; startClass(c); try { Field[] fields = c.getDeclaredFields(); Arrays.sort(fields, new Comparator() { public int compare(Object o1, Object o2) { return ((Field) o1).getName().compareTo(((Field) o2).getName()); } }); for (i = 0; i < fields.length; i++) { Field field = (Field) fields[i]; if (!Modifier.isPrivate(field.getModifiers())) putField(field, c); // else System.err.println("private field ignored: " + field); } Method methods[] = c.getDeclaredMethods(); // Arrays.sort(methods); for (i = 0; i < methods.length; i++) { if (!Modifier.isPrivate(methods[i].getModifiers())) putMethod(methods[i], c); // else System.err.println("pvt: " + methods[i]); } } catch (Exception e) { e.printStackTrace(); } endClass(); }
From source file:de.taimos.dvalin.interconnect.core.spring.InterconnectBeanPostProcessor.java
private InjectionMetadata buildResourceMetadata(Class<?> clazz) { LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>(); Class<?> targetClass = clazz; do {//from w w w .j av a 2 s .com LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>(); for (Field field : targetClass.getDeclaredFields()) { if (field.isAnnotationPresent(Interconnect.class)) { if (Modifier.isStatic(field.getModifiers())) { throw new IllegalStateException( "@Interconnect annotation is not supported on static fields"); } currElements.add(new InterconnectElement(field, null)); } } for (Method method : targetClass.getDeclaredMethods()) { Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { continue; } if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (bridgedMethod.isAnnotationPresent(Interconnect.class)) { if (Modifier.isStatic(method.getModifiers())) { throw new IllegalStateException( "@Interconnect annotation is not supported on static methods"); } if (method.getParameterTypes().length != 1) { throw new IllegalStateException( "@Interconnect annotation requires a single-arg method: " + method); } PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); currElements.add(new InterconnectElement(method, pd)); } } } elements.addAll(0, currElements); targetClass = targetClass.getSuperclass(); } while ((targetClass != null) && (targetClass != Object.class)); return new InjectionMetadata(clazz, elements); }
From source file:com.opensymphony.xwork2.util.finder.ClassFinder.java
public List<Method> findAnnotatedMethods(Class<? extends Annotation> annotation) { classesNotLoaded.clear();/*from w ww. ja va2s. com*/ List<ClassInfo> seen = new ArrayList<ClassInfo>(); List<Method> methods = new ArrayList<Method>(); List<Info> infos = getAnnotationInfos(annotation.getName()); for (Info info : infos) { if (info instanceof MethodInfo && !"<init>".equals(info.getName())) { MethodInfo methodInfo = (MethodInfo) info; ClassInfo classInfo = methodInfo.getDeclaringClass(); if (seen.contains(classInfo)) continue; seen.add(classInfo); try { Class clazz = classInfo.get(); for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(annotation)) { methods.add(method); } } } catch (Throwable e) { if (LOG.isErrorEnabled()) LOG.error("Error loading class [#0]", e, classInfo.getName()); classesNotLoaded.add(classInfo.getName()); } } } return methods; }
From source file:org.apache.openejb.config.CleanEnvEntries.java
private Class<?> getType(final ClassLoader loader, final InjectionTarget target) { try {/*from w w w . j av a 2s .c o m*/ final Class<?> clazz = loader.loadClass(target.getInjectionTargetClass()); try { final Field field = clazz.getDeclaredField(target.getInjectionTargetName()); return field.getType(); } catch (final NoSuchFieldException e) { // no-op } // TODO Technically we should match by case final String bestName = "set" + StringUtils.capitalize(target.getInjectionTargetName()); final String name = "set" + target.getInjectionTargetName().toLowerCase(); Class<?> found = null; for (final Method method : clazz.getDeclaredMethods()) { if (method.getParameterTypes().length == 1) { if (method.getName().equals(bestName)) { return method.getParameterTypes()[0]; } else if (method.getName().toLowerCase().equals(name)) { found = method.getParameterTypes()[0]; } } } if (found != null) { return found; } } catch (final Throwable e) { // no-op } return Object.class; }
From source file:com.p5solutions.core.utils.ReflectionUtility.java
/** * Find all methods.// ww w.j a v a 2s . co m * * @param clazz * the clazz * @return the list */ public static List<Method> findAllMethods(Class<?> clazz) { List<Method> methods = new ArrayList<Method>(); // Iterate each method for (Method method : clazz.getDeclaredMethods()) { methods.add(method); } // recursively build list of methods Class<?> superClazz = clazz.getSuperclass(); if (superClazz != null) { List<Method> superMethods = findAllMethods(superClazz); methods.addAll(superMethods); } return methods; }
From source file:de.taimos.dvalin.jaxrs.remote.RemoteServiceBeanPostProcessor.java
private InjectionMetadata buildResourceMetadata(Class<?> clazz) { LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>(); Class<?> targetClass = clazz; do {//from www. ja va2 s .co m LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>(); for (Field field : targetClass.getDeclaredFields()) { if (field.isAnnotationPresent(RemoteService.class)) { if (Modifier.isStatic(field.getModifiers())) { throw new IllegalStateException( "@RemoteService annotation is not supported on static fields"); } currElements.add(new RemoteServiceElement(field, field, null)); } } for (Method method : targetClass.getDeclaredMethods()) { Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { continue; } if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (bridgedMethod.isAnnotationPresent(RemoteService.class)) { if (Modifier.isStatic(method.getModifiers())) { throw new IllegalStateException( "@RemoteService annotation is not supported on static methods"); } if (method.getParameterTypes().length != 1) { throw new IllegalStateException( "@RemoteService annotation requires a single-arg method: " + method); } PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); currElements.add(new RemoteServiceElement(method, bridgedMethod, pd)); } } } elements.addAll(0, currElements); targetClass = targetClass.getSuperclass(); } while ((targetClass != null) && (targetClass != Object.class)); return new InjectionMetadata(clazz, elements); }
From source file:org.ff4j.aop.FeatureAutoProxy.java
private Object[] addAnnotedInterface(Class<?> currentInterface) { String currentInterfaceName = currentInterface.getCanonicalName(); if (!currentInterfaceName.startsWith("java.")) { // Avoid process same interface several times Boolean isInterfaceFlipped = processedInterface.get(currentInterfaceName); if (isInterfaceFlipped != null) { if (isInterfaceFlipped) { return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS; }// w w w .j a va2s . co m } else { if (currentInterface.isAnnotationPresent(Flip.class)) { // If annotation is registered on Interface class processedInterface.put(currentInterfaceName, true); return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS; } else { for (Method method : currentInterface.getDeclaredMethods()) { if (method.isAnnotationPresent(Flip.class)) { processedInterface.put(currentInterfaceName, true); return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS; } } processedInterface.put(currentInterfaceName, false); } } } return null; }
From source file:org.appcelerator.locator.AnnotationBasedLocator.java
/** * use this to scan for services after our first run *///from w w w . j a va2s. c o m public synchronized void rescan() { this.candidateServices = Arrays.asList(AnnotationHelper.findAnnotation(Service.class)); boolean first = true; //refresh the spring context the first time for (Class<?> service : this.candidateServices) { Object instance = null; Service serviceAnnotation = findFirstMethodAnnotation(service, Service.class); Set<ServiceAdapter> adapters = serviceAnnotation == null ? null : ServiceRegistry.getRegisteredServices(serviceAnnotation.request()); if (adapters != null) { for (ServiceAdapter adapter : adapters) { if (adapter instanceof MethodCallServiceAdapter) { instance = ((MethodCallServiceAdapter) adapter).getInstance(); } } } if (!Springer.doSpringBean(service, servletContext, first)) { first = false; for (Method method : service.getDeclaredMethods()) { instance = RegistrarUtil.registerServiceMethod(method, service, instance); instance = RegistrarUtil.registerDownloadableMethod(method, service, instance); } } } }
From source file:hu.bme.mit.sette.common.tasks.TestSuiteRunner.java
private void analyzeOne(Snippet snippet, File[] binaryDirectories) throws Exception { String snippetClassName = snippet.getContainer().getJavaClass().getName(); String snippetMethodName = snippet.getMethod().getName(); String testClassName = snippet.getContainer().getJavaClass().getName() + "_" + snippet.getMethod().getName() + "_Tests"; logger.debug("Snippet: {}#{}()", snippetClassName, snippetMethodName); logger.debug("Tests: {}", testClassName); // create JaCoCo runtime and instrumenter IRuntime runtime = new LoggerRuntime(); Instrumenter instrumenter = new Instrumenter(runtime); // start runtime RuntimeData data = new RuntimeData(); runtime.startup(data);//from www . j a v a 2 s . c o m // create class loader JaCoCoClassLoader classLoader = new JaCoCoClassLoader(binaryDirectories, instrumenter, getSnippetProject().getClassLoader()); // load test class // snippet class and other dependencies will be loaded and instrumented // on the fly Class<?> testClass = classLoader.loadClass(testClassName); TestCase testClassInstance = (TestCase) testClass.newInstance(); // invoke test methods // TODO separate collect and invoke for (Method m : testClass.getDeclaredMethods()) { if (m.isSynthetic()) { // skip synthetic method continue; } if (m.getName().startsWith("test")) { logger.trace("Invoking: " + m.getName()); try { m.invoke(testClassInstance); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof NullPointerException || cause instanceof ArrayIndexOutOfBoundsException || cause instanceof AssertionFailedError) { logger.warn(cause.getClass().getName() + ": " + m.getDeclaringClass().getName() + "." + m.getName()); } else { logger.error("Exception: " + m.getDeclaringClass().getName() + "." + m.getName()); } logger.debug(e.getMessage(), e); } } else { logger.warn("Not test method: {}", m.getName()); } } // collect data ExecutionDataStore executionData = new ExecutionDataStore(); SessionInfoStore sessionInfos = new SessionInfoStore(); data.collect(executionData, sessionInfos, false); runtime.shutdown(); // get classes to analyse // store string to avoid the mess up between the different class loaders Set<String> javaClasses = new HashSet<>(); javaClasses.add(snippetClassName); for (Constructor<?> inclConstructor : snippet.getIncludedConstructors()) { javaClasses.add(inclConstructor.getDeclaringClass().getName()); } for (Method inclMethod : snippet.getIncludedMethods()) { javaClasses.add(inclMethod.getDeclaringClass().getName()); } // TODO inner classes are not handled well enough // TODO anonymous classes can also have anonymous classes -> recursion Set<String> toAdd = new HashSet<>(); for (String javaClass : javaClasses) { int i = 1; while (true) { // guess anonymous classes, like ClassName$1, ClassName$2 etc. try { classLoader.loadClass(javaClass + "$" + i); toAdd.add(javaClass + "$" + i); i++; } catch (ClassNotFoundException e) { // bad guess, no more anonymous classes on this level break; } } } javaClasses.addAll(toAdd); // analyse classes CoverageBuilder coverageBuilder = new CoverageBuilder(); Analyzer analyzer = new Analyzer(executionData, coverageBuilder); for (String javaClassName : javaClasses) { logger.trace("Analysing: {}", javaClassName); analyzer.analyzeClass(classLoader.readBytes(javaClassName), javaClassName); } // TODO remove debug // new File("D:/SETTE/!DUMP/" + getTool().getName()).mkdirs(); // PrintStream out = new PrintStream("D:/SETTE/!DUMP/" // + getTool().getName() + "/" + testClassName + ".out"); Map<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> coverageInfo = new HashMap<>(); for (final IClassCoverage cc : coverageBuilder.getClasses()) { String file = cc.getPackageName() + '/' + cc.getSourceFileName(); file = file.replace('\\', '/'); if (!coverageInfo.containsKey(file)) { coverageInfo.put(file, Triple.of(new TreeSet<Integer>(), new TreeSet<Integer>(), new TreeSet<Integer>())); } // out.printf("Coverage of class %s%n", cc.getName()); // // printCounter(out, "instructions", // cc.getInstructionCounter()); // printCounter(out, "branches", cc.getBranchCounter()); // printCounter(out, "lines", cc.getLineCounter()); // printCounter(out, "methods", cc.getMethodCounter()); // printCounter(out, "complexity", cc.getComplexityCounter()); for (int l = cc.getFirstLine(); l <= cc.getLastLine(); l++) { switch (cc.getLine(l).getStatus()) { case ICounter.FULLY_COVERED: coverageInfo.get(file).getLeft().add(l); break; case ICounter.PARTLY_COVERED: coverageInfo.get(file).getMiddle().add(l); break; case ICounter.NOT_COVERED: coverageInfo.get(file).getRight().add(l); break; } } } // create coverage XML SnippetCoverageXml coverageXml = new SnippetCoverageXml(); coverageXml.setToolName(getTool().getName()); coverageXml.setSnippetProjectElement( new SnippetProjectElement(getSnippetProjectSettings().getBaseDirectory().getCanonicalPath())); coverageXml.setSnippetElement( new SnippetElement(snippet.getContainer().getJavaClass().getName(), snippet.getMethod().getName())); coverageXml.setResultType(ResultType.S); for (Entry<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> entry : coverageInfo .entrySet()) { TreeSet<Integer> full = entry.getValue().getLeft(); TreeSet<Integer> partial = entry.getValue().getMiddle(); TreeSet<Integer> not = entry.getValue().getRight(); FileCoverageElement fce = new FileCoverageElement(); fce.setName(entry.getKey()); fce.setFullyCoveredLines(StringUtils.join(full, ' ')); fce.setPartiallyCoveredLines(StringUtils.join(partial, ' ')); fce.setNotCoveredLines(StringUtils.join(not, ' ')); coverageXml.getCoverage().add(fce); } coverageXml.validate(); // TODO needs more documentation File coverageFile = RunnerProjectUtils.getSnippetCoverageFile(getRunnerProjectSettings(), snippet); Serializer serializer = new Persister(new AnnotationStrategy(), new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>")); serializer.write(coverageXml, coverageFile); // TODO move HTML generation to another file/phase File htmlFile = RunnerProjectUtils.getSnippetHtmlFile(getRunnerProjectSettings(), snippet); String htmlTitle = getTool().getName() + " - " + snippetClassName + '.' + snippetMethodName + "()"; StringBuilder htmlData = new StringBuilder(); htmlData.append("<!DOCTYPE html>\n"); htmlData.append("<html lang=\"hu\">\n"); htmlData.append("<head>\n"); htmlData.append(" <meta charset=\"utf-8\" />\n"); htmlData.append(" <title>" + htmlTitle + "</title>\n"); htmlData.append(" <style type=\"text/css\">\n"); htmlData.append(" .code { font-family: 'Consolas', monospace; }\n"); htmlData.append(" .code .line { border-bottom: 1px dotted #aaa; white-space: pre; }\n"); htmlData.append(" .code .green { background-color: #CCFFCC; }\n"); htmlData.append(" .code .yellow { background-color: #FFFF99; }\n"); htmlData.append(" .code .red { background-color: #FFCCCC; }\n"); htmlData.append(" .code .line .number {\n"); htmlData.append(" display: inline-block;\n"); htmlData.append(" width:50px;\n"); htmlData.append(" text-align:right;\n"); htmlData.append(" margin-right:5px;\n"); htmlData.append(" }\n"); htmlData.append(" </style>\n"); htmlData.append("</head>\n"); htmlData.append("\n"); htmlData.append("<body>\n"); htmlData.append(" <h1>" + htmlTitle + "</h1>\n"); for (FileCoverageElement fce : coverageXml.getCoverage()) { htmlData.append(" <h2>" + fce.getName() + "</h2>\n"); htmlData.append(" \n"); File src = new File(getSnippetProject().getSettings().getSnippetSourceDirectory(), fce.getName()); List<String> srcLines = FileUtils.readLines(src); SortedSet<Integer> full = linesToSortedSet(fce.getFullyCoveredLines()); SortedSet<Integer> partial = linesToSortedSet(fce.getPartiallyCoveredLines()); SortedSet<Integer> not = linesToSortedSet(fce.getNotCoveredLines()); htmlData.append(" <div class=\"code\">\n"); int i = 1; for (String srcLine : srcLines) { String divClass = getLineDivClass(i, full, partial, not); htmlData.append(" <div class=\"" + divClass + "\"><div class=\"number\">" + i + "</div> " + srcLine + "</div>\n"); i++; } htmlData.append(" </div>\n\n"); } // htmlData.append(" <div class=\"line\"><div class=\"number\">1</div> package samplesnippets;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">2</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">3</div> import hu.bme.mit.sette.annotations.SetteIncludeCoverage;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">4</div> import hu.bme.mit.sette.annotations.SetteNotSnippet;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">5</div> import hu.bme.mit.sette.annotations.SetteRequiredStatementCoverage;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">6</div> import hu.bme.mit.sette.annotations.SetteSnippetContainer;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">7</div> import samplesnippets.inputs.SampleContainer_Inputs;</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">8</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">9</div> @SetteSnippetContainer(category = "X1",</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">10</div> goal = "Sample // snippet container",</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">11</div> inputFactoryContainer = SampleContainer_Inputs.class)</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">12</div> public final class SampleContainer {</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">13</div> private SampleContainer() {</div>\n"); // htmlData.append(" <div class=\"line red\"><div class=\"number\">14</div> throw new UnsupportedOperationException("Static // class");</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">15</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">16</div> </div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">17</div> @SetteRequiredStatementCoverage(value = 100)</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">18</div> public static boolean snippet(int x) {</div>\n"); // htmlData.append(" <div class=\"line yellow\"><div class=\"number\">19</div> if (20 * x + 2 == 42) {</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">20</div> return true;</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">21</div> } else {</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">22</div> return false;</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">23</div> }</div>\n"); // htmlData.append(" <div class=\"line green\"><div class=\"number\">24</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">25</div> }</div>\n"); // htmlData.append(" <div class=\"line\"><div class=\"number\">26</div> </div>\n"); htmlData.append("</body>\n"); htmlData.append("</html>\n"); FileUtils.write(htmlFile, htmlData); }
From source file:org.apache.openjpa.persistence.AnnotationPersistenceXMLMetaDataParser.java
private void populateFromReflection(Class cls, XMLMetaData meta) { Member[] members;/*from w w w . j a v a2s . c o m*/ Class superclass = cls.getSuperclass(); // handle inheritance at sub-element level if ((AccessController.doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(superclass, xmlTypeClass))) .booleanValue()) populateFromReflection(superclass, meta); try { if (StringUtils.equals( xmlAccessorValue.invoke(cls.getAnnotation(xmlAccessorTypeClass), new Object[] {}).toString(), "FIELD")) members = cls.getDeclaredFields(); else members = cls.getDeclaredMethods(); for (int i = 0; i < members.length; i++) { Member member = members[i]; AnnotatedElement el = (AnnotatedElement) member; XMLMetaData field = null; if (el.getAnnotation(xmlElementClass) != null) { String xmlname = (String) xmlElementName.invoke(el.getAnnotation(xmlElementClass), new Object[] {}); // avoid JAXB XML bind default name if (StringUtils.equals(XMLMetaData.defaultName, xmlname)) xmlname = member.getName(); if ((AccessController.doPrivileged( J2DoPrivHelper.isAnnotationPresentAction(((Field) member).getType(), xmlTypeClass))) .booleanValue()) { field = _repos.addXMLClassMetaData(((Field) member).getType()); parseXmlRootElement(((Field) member).getType(), field); populateFromReflection(((Field) member).getType(), field); field.setXmltype(XMLMetaData.XMLTYPE); field.setXmlname(xmlname); } else { field = _repos.newXMLFieldMetaData(((Field) member).getType(), member.getName()); field.setXmltype(XMLMetaData.ELEMENT); field.setXmlname(xmlname); field.setXmlnamespace((String) xmlElementNamespace.invoke(el.getAnnotation(xmlElementClass), new Object[] {})); } } else if (el.getAnnotation(xmlAttributeClass) != null) { field = _repos.newXMLFieldMetaData(((Field) member).getType(), member.getName()); field.setXmltype(XMLFieldMetaData.ATTRIBUTE); String xmlname = (String) xmlAttributeName.invoke(el.getAnnotation(xmlAttributeClass), new Object[] {}); // avoid JAXB XML bind default name if (StringUtils.equals(XMLMetaData.defaultName, xmlname)) xmlname = member.getName(); field.setXmlname("@" + xmlname); field.setXmlnamespace((String) xmlAttributeNamespace.invoke(el.getAnnotation(xmlAttributeClass), new Object[] {})); } if (field != null) meta.addField(member.getName(), field); } } catch (Exception e) { } }