Example usage for java.lang Class getDeclaredMethods

List of usage examples for java.lang Class getDeclaredMethods

Introduction

In this page you can find the example usage for java.lang Class getDeclaredMethods.

Prototype

@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Usage

From source file:com.sawyer.advadapters.widget.JSONAdapter.java

/**
 * Scans all subclasses of this instance for any isFilteredOut methods and caches them for later
 * invocation.//from   ww w.  j a  v  a  2  s . com
 */
private void cacheSubclassFilteredMethods() {
    //Scan public methods first
    Class<?> c = this.getClass();
    Method[] methods = c.getMethods();
    for (Method m : methods) {
        String key = getFilterMethodKey(m);
        if (key != null)
            mFilterMethods.put(key, m);
    }

    //Scan non-public methods next
    while (!c.equals(JSONAdapter.class)) {
        methods = c.getDeclaredMethods();
        for (Method m : methods) {
            String key = getFilterMethodKey(m);
            if (key != null) {
                m.setAccessible(true);
                mFilterMethods.put(key, m);
            }
        }
        c = c.getSuperclass();
    }
}

From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

private HashMap<Method, String> getFieldMapping(Class cls, int type, Boolean isCamelCased,
        Boolean useDeclaredOnly) {
    HashMap<Method, String> fieldMapping = new HashMap<>();
    Method[] methods;/*from  w  w  w.j  av a 2s .  c om*/
    if (useDeclaredOnly) {
        methods = cls.getDeclaredMethods();
    } else {
        methods = cls.getMethods();
    }
    for (Method method : methods) {
        if (method.getAnnotation(Transient.class) == null) {
            String methodName = method.getName();
            if (type == GET) {
                if (methodName.startsWith("get") && !methodName.equals("getClass")) {
                    fieldMapping.put(method, getDbName(isCamelCased, methodName.substring(3), method));
                }
            } else {
                if (methodName.startsWith("set") && !methodName.equals("getClass")) {
                    fieldMapping.put(method, getDbName(isCamelCased, methodName.substring(3), method));
                }
            }
        }
    }
    return fieldMapping;
}

From source file:io.stallion.restfulEndpoints.ResourceToEndpoints.java

public List<JavaRestEndpoint> convert(EndpointResource resource) {
    Class cls = resource.getClass();
    List<JavaRestEndpoint> endpoints = new ArrayList<>();

    // Get defaults from the resource

    Role defaultMinRole = Settings.instance().getUsers().getDefaultEndpointRoleObj();
    MinRole minRoleAnno = (MinRole) cls.getAnnotation(MinRole.class);
    if (minRoleAnno != null) {
        defaultMinRole = minRoleAnno.value();
    }//from w w  w . j av  a  2s.  c o  m

    String defaultProduces = "text/html";
    Produces producesAnno = (Produces) cls.getAnnotation(Produces.class);
    if (producesAnno != null && producesAnno.value().length > 0) {
        defaultProduces = producesAnno.value()[0];
    }

    Path pathAnno = (Path) cls.getAnnotation(Path.class);
    if (pathAnno != null) {
        basePath += pathAnno.value();
    }

    Class defaultJsonViewClass = null;
    DefaultJsonView jsonView = (DefaultJsonView) cls.getAnnotation(DefaultJsonView.class);
    if (jsonView != null) {
        defaultJsonViewClass = jsonView.value();
    }

    for (Method method : cls.getDeclaredMethods()) {
        JavaRestEndpoint endpoint = new JavaRestEndpoint();
        endpoint.setRole(defaultMinRole);
        endpoint.setProduces(defaultProduces);
        if (defaultJsonViewClass != null) {
            endpoint.setJsonViewClass(defaultJsonViewClass);
        }

        Log.finer("Resource class method: {0}", method.getName());
        for (Annotation anno : method.getDeclaredAnnotations()) {
            if (Path.class.isInstance(anno)) {
                Path pth = (Path) anno;
                endpoint.setRoute(getBasePath() + pth.value());
            } else if (GET.class.isInstance(anno)) {
                endpoint.setMethod("GET");
            } else if (POST.class.isInstance(anno)) {
                endpoint.setMethod("POST");
            } else if (DELETE.class.isInstance(anno)) {
                endpoint.setMethod("DELETE");
            } else if (PUT.class.isInstance(anno)) {
                endpoint.setMethod("PUT");
            } else if (Produces.class.isInstance(anno)) {
                endpoint.setProduces(((Produces) anno).value()[0]);
            } else if (MinRole.class.isInstance(anno)) {
                endpoint.setRole(((MinRole) anno).value());
            } else if (XSRF.class.isInstance(anno)) {
                endpoint.setCheckXSRF(((XSRF) anno).value());
            } else if (JsonView.class.isInstance(anno)) {
                Class[] classes = ((JsonView) anno).value();
                if (classes == null || classes.length != 1) {
                    throw new UsageException("JsonView annotation for method " + method.getName()
                            + " must have exactly one view class");
                }
                endpoint.setJsonViewClass(classes[0]);
            }
        }
        if (!empty(endpoint.getMethod()) && !empty(endpoint.getRoute())) {
            endpoint.setJavaMethod(method);
            endpoint.setResource(resource);
            endpoints.add(endpoint);
            Log.fine("Register endpoint {0} {1}", endpoint.getMethod(), endpoint.getRoute());
        } else {
            continue;
        }
        int x = -1;
        for (Parameter param : method.getParameters()) {
            x++;
            RequestArg arg = new RequestArg();
            for (Annotation anno : param.getAnnotations()) {
                arg.setAnnotationInstance(anno);
                Log.finer("Param Annotation is: {0}, {1}", anno, anno.getClass().getName());
                if (BodyParam.class.isInstance(anno)) {
                    BodyParam bodyAnno = (BodyParam) (anno);
                    arg.setType("BodyParam");
                    if (empty(bodyAnno.value())) {
                        arg.setName(param.getName());
                    } else {
                        arg.setName(((BodyParam) anno).value());
                    }
                    arg.setAnnotationClass(BodyParam.class);
                    arg.setRequired(bodyAnno.required());
                    arg.setEmailParam(bodyAnno.isEmail());
                    arg.setMinLength(bodyAnno.minLength());
                    arg.setAllowEmpty(bodyAnno.allowEmpty());
                    if (!empty(bodyAnno.validationPattern())) {
                        arg.setValidationPattern(Pattern.compile(bodyAnno.validationPattern()));
                    }
                } else if (ObjectParam.class.isInstance(anno)) {
                    ObjectParam oParam = (ObjectParam) anno;
                    arg.setType("ObjectParam");
                    arg.setName("noop");
                    if (oParam.targetClass() == null || oParam.targetClass().equals(Object.class)) {
                        arg.setTargetClass(param.getType());
                    } else {
                        arg.setTargetClass(oParam.targetClass());
                    }
                    arg.setAnnotationClass(ObjectParam.class);
                } else if (MapParam.class.isInstance(anno)) {
                    arg.setType("MapParam");
                    arg.setName("noop");
                    arg.setAnnotationClass(MapParam.class);
                } else if (QueryParam.class.isInstance(anno)) {
                    arg.setType("QueryParam");
                    arg.setName(((QueryParam) anno).value());
                    arg.setAnnotationClass(QueryParam.class);
                } else if (PathParam.class.isInstance(anno)) {
                    arg.setType("PathParam");
                    arg.setName(((PathParam) anno).value());
                    arg.setAnnotationClass(PathParam.class);
                } else if (DefaultValue.class.isInstance(anno)) {
                    arg.setDefaultValue(((DefaultValue) anno).value());
                } else if (NotNull.class.isInstance(anno)) {
                    arg.setRequired(true);
                } else if (Nullable.class.isInstance(anno)) {
                    arg.setRequired(false);
                } else if (NotEmpty.class.isInstance(anno)) {
                    arg.setRequired(true);
                    arg.setAllowEmpty(false);
                } else if (Email.class.isInstance(anno)) {
                    arg.setEmailParam(true);
                }
            }
            if (StringUtils.isEmpty(arg.getType())) {
                arg.setType("ObjectParam");
                arg.setName(param.getName());
                arg.setTargetClass(param.getType());
                arg.setAnnotationClass(ObjectParam.class);
            }

            if (StringUtils.isEmpty(arg.getName())) {
                arg.setName(param.getName());
            }
            endpoint.getArgs().add(arg);
        }
    }
    return endpoints;
}

From source file:com.gargoylesoftware.htmlunit.CodeStyleTest.java

private void testTests(final File dir) throws Exception {
    for (final File file : dir.listFiles()) {
        if (file.isDirectory()) {
            if (!".svn".equals(file.getName())) {
                testTests(file);/*from www  .  j  a  v  a 2  s .c om*/
            }
        } else {
            if (file.getName().endsWith(".java")) {
                final int index = new File("src/test/java").getAbsolutePath().length();
                String name = file.getAbsolutePath();
                name = name.substring(index + 1, name.length() - 5);
                name = name.replace(File.separatorChar, '.');
                final Class<?> clazz;
                try {
                    clazz = Class.forName(name);
                } catch (final Exception e) {
                    continue;
                }
                name = file.getName();
                if (name.endsWith("Test.java") || name.endsWith("TestCase.java")) {
                    for (final Constructor<?> ctor : clazz.getConstructors()) {
                        if (ctor.getParameterTypes().length == 0) {
                            for (final Method method : clazz.getDeclaredMethods()) {
                                if (Modifier.isPublic(method.getModifiers())
                                        && method.getAnnotation(Before.class) == null
                                        && method.getAnnotation(BeforeClass.class) == null
                                        && method.getAnnotation(After.class) == null
                                        && method.getAnnotation(AfterClass.class) == null
                                        && method.getAnnotation(Test.class) == null
                                        && method.getReturnType() == Void.TYPE
                                        && method.getParameterTypes().length == 0) {
                                    fail("Method '" + method.getName() + "' in " + name
                                            + " does not declare @Test annotation");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:com.zero_x_baadf00d.partialize.Partialize.java

/**
 * Build a JSON object from data taken from the scanner and
 * the given class type and instance./*from w  w w  .  j a v  a  2  s  .  co m*/
 *
 * @param depth         The current depth
 * @param fields        The field names to requests
 * @param clazz         The class of the object to render
 * @param instance      The instance of the object to render
 * @param partialObject The partial JSON document
 * @return A JSON Object
 * @since 16.01.18
 */
private ObjectNode buildPartialObject(final int depth, String fields, final Class<?> clazz,
        final Object instance, final ObjectNode partialObject) {
    if (depth <= this.maximumDepth) {
        if (clazz.isAnnotationPresent(com.zero_x_baadf00d.partialize.annotation.Partialize.class)) {
            final List<String> closedFields = new ArrayList<>();
            List<String> allowedFields = Arrays.asList(clazz
                    .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).allowedFields());
            List<String> defaultFields = Arrays.asList(clazz
                    .getAnnotation(com.zero_x_baadf00d.partialize.annotation.Partialize.class).defaultFields());
            if (allowedFields.isEmpty()) {
                allowedFields = new ArrayList<>();
                for (final Method m : clazz.getDeclaredMethods()) {
                    final String methodName = m.getName();
                    if (methodName.startsWith("get") || methodName.startsWith("has")) {
                        final char[] c = methodName.substring(3).toCharArray();
                        c[0] = Character.toLowerCase(c[0]);
                        allowedFields.add(new String(c));
                    } else if (methodName.startsWith("is")) {
                        final char[] c = methodName.substring(2).toCharArray();
                        c[0] = Character.toLowerCase(c[0]);
                        allowedFields.add(new String(c));
                    }
                }
            }
            if (defaultFields.isEmpty()) {
                defaultFields = allowedFields.stream().map(f -> {
                    if (this.aliases != null && this.aliases.containsValue(f)) {
                        for (Map.Entry<String, String> e : this.aliases.entrySet()) {
                            if (e.getValue().compareToIgnoreCase(f) == 0) {
                                return e.getKey();
                            }
                        }
                    }
                    return f;
                }).collect(Collectors.toList());
            }
            if (fields == null || fields.length() == 0) {
                fields = defaultFields.stream().collect(Collectors.joining(","));
            }
            Scanner scanner = new Scanner(fields);
            scanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER);
            while (scanner.hasNext()) {
                String word = scanner.next();
                String args = null;
                if (word.compareTo("*") == 0) {
                    final StringBuilder sb = new StringBuilder();
                    if (scanner.hasNext()) {
                        scanner.useDelimiter("\n");
                        sb.append(",");
                        sb.append(scanner.next());
                    }
                    final Scanner newScanner = new Scanner(
                            allowedFields.stream().filter(f -> !closedFields.contains(f)).map(f -> {
                                if (this.aliases != null && this.aliases.containsValue(f)) {
                                    for (Map.Entry<String, String> e : this.aliases.entrySet()) {
                                        if (e.getValue().compareToIgnoreCase(f) == 0) {
                                            return e.getKey();
                                        }
                                    }
                                }
                                return f;
                            }).collect(Collectors.joining(",")) + sb.toString());
                    newScanner.useDelimiter(com.zero_x_baadf00d.partialize.Partialize.SCANNER_DELIMITER);
                    scanner.close();
                    scanner = newScanner;
                }
                if (word.contains("(")) {
                    while (scanner.hasNext()
                            && (StringUtils.countMatches(word, "(") != StringUtils.countMatches(word, ")"))) {
                        word += "," + scanner.next();
                    }
                    final Matcher m = this.fieldArgsPattern.matcher(word);
                    if (m.find()) {
                        word = m.group(1);
                        args = m.group(2);
                    }
                }
                final String aliasField = word;
                final String field = this.aliases != null && this.aliases.containsKey(aliasField)
                        ? this.aliases.get(aliasField)
                        : aliasField;
                if (allowedFields.stream().anyMatch(
                        f -> f.toLowerCase(Locale.ENGLISH).compareTo(field.toLowerCase(Locale.ENGLISH)) == 0)) {
                    if (this.accessPolicyFunction != null
                            && !this.accessPolicyFunction.apply(new AccessPolicy(clazz, instance, field))) {
                        continue;
                    }
                    closedFields.add(aliasField);
                    try {
                        final Method method = clazz.getMethod("get" + WordUtils.capitalize(field));
                        final Object object = method.invoke(instance);
                        this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object);
                    } catch (IllegalAccessException | InvocationTargetException
                            | NoSuchMethodException ignore) {
                        try {
                            final Method method = clazz.getMethod(field);
                            final Object object = method.invoke(instance);
                            this.internalBuild(depth, aliasField, field, args, partialObject, clazz, object);
                        } catch (IllegalAccessException | InvocationTargetException
                                | NoSuchMethodException ex) {
                            if (this.exceptionConsumer != null) {
                                this.exceptionConsumer.accept(ex);
                            }
                        }
                    }
                }
            }
            return partialObject;
        } else if (instance instanceof Map<?, ?>) {
            if (fields == null || fields.isEmpty() || fields.compareTo("*") == 0) {
                for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) {
                    this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()), null,
                            partialObject, e.getValue() == null ? Object.class : e.getValue().getClass(),
                            e.getValue());
                }
            } else {
                final Map<?, ?> tmpMap = (Map<?, ?>) instance;
                for (final String k : fields.split(",")) {
                    if (k.compareTo("*") != 0) {
                        final Object o = tmpMap.get(k);
                        this.internalBuild(depth, k, k, null, partialObject,
                                o == null ? Object.class : o.getClass(), o);
                    } else {
                        for (Map.Entry<?, ?> e : ((Map<?, ?>) instance).entrySet()) {
                            this.internalBuild(depth, String.valueOf(e.getKey()), String.valueOf(e.getKey()),
                                    null, partialObject,
                                    e.getValue() == null ? Object.class : e.getValue().getClass(),
                                    e.getValue());
                        }
                    }
                }
            }
        } else {
            throw new RuntimeException("Can't convert " + clazz.getCanonicalName());
        }
    }
    return partialObject;
}

From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java

private <R> Map<String, GetSetPair> getGetSetPairs(Class<R> recordClass) throws Exception {
    Map<String, GetSetPair> ret = new HashMap<String, GetSetPair>();
    Method[] methods = recordClass.getDeclaredMethods();
    // get all get methods
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];//from  w  w  w  . j a  v a2s .c om
        int mod = m.getModifiers();
        if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) {
            String name = m.getName();
            if (name.equals("getProto")) {
                continue;
            }
            if ((name.length() > 3) && name.startsWith("get") && (m.getParameterTypes().length == 0)) {
                String propertyName = name.substring(3);
                Type valueType = m.getGenericReturnType();
                GetSetPair p = ret.get(propertyName);
                if (p == null) {
                    p = new GetSetPair();
                    p.propertyName = propertyName;
                    p.type = valueType;
                    p.getMethod = m;
                    ret.put(propertyName, p);
                } else {
                    Assert.fail("Multiple get method with same name: " + recordClass + p.propertyName);
                }
            }
        }
    }
    // match get methods with set methods
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        int mod = m.getModifiers();
        if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) {
            String name = m.getName();
            if (name.startsWith("set") && (m.getParameterTypes().length == 1)) {
                String propertyName = name.substring(3);
                Type valueType = m.getGenericParameterTypes()[0];
                GetSetPair p = ret.get(propertyName);
                if (p != null && p.type.equals(valueType)) {
                    p.setMethod = m;
                }
            }
        }
    }
    // exclude incomplete get/set pair, and generate test value
    Iterator<Entry<String, GetSetPair>> itr = ret.entrySet().iterator();
    while (itr.hasNext()) {
        Entry<String, GetSetPair> cur = itr.next();
        GetSetPair gsp = cur.getValue();
        if ((gsp.getMethod == null) || (gsp.setMethod == null)) {
            LOG.info(String.format("Exclude protential property: %s\n", gsp.propertyName));
            itr.remove();
        } else {
            LOG.info(String.format("New property: %s type: %s", gsp.toString(), gsp.type));
            gsp.testValue = genTypeValue(gsp.type);
            LOG.info(String.format(" testValue: %s\n", gsp.testValue));
        }
    }
    return ret;
}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

private static ArrayList<Class> getClassesFromDirectory(String pkg, ClassLoader cl)
        throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname. There may be more than one if a package is split over multiple jars/paths
    String pckgname = pkg;/*  www  . ja  v a2  s.co  m*/
    ArrayList<File> directories = new ArrayList<File>();
    try {
        String path = pckgname.replace('.', '/');
        // Ask for all resources for the path
        Enumeration<URL> resources = cl.getResources(path);
        while (resources.hasMoreElements()) {
            directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        if (log.isDebugEnabled()) {
            log.debug(pckgname + " does not appear to be a valid package (Unsupported encoding)");
        }
        throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr2", pckgname));
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("IOException was thrown when trying to get all resources for " + pckgname);
        }
        throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr3", pckgname));
    }

    ArrayList<Class> classes = new ArrayList<Class>();
    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (log.isDebugEnabled()) {
            log.debug("  Adding JAXB classes from directory: " + directory.getName());
        }
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                // we are only interested in .class files
                if (file.endsWith(".class")) {
                    // removes the .class extension
                    // TODO Java2 Sec
                    String className = pckgname + '.' + file.substring(0, file.length() - 6);
                    try {
                        Class clazz = forName(className, false, getContextClassLoader());
                        // Don't add any interfaces or JAXWS specific classes.  
                        // Only classes that represent data and can be marshalled 
                        // by JAXB should be added.
                        if (!clazz.isInterface()
                                && (clazz.isEnum() || getAnnotation(clazz, XmlType.class) != null
                                        || ClassUtils.getDefaultPublicConstructor(clazz) != null)
                                && !ClassUtils.isJAXWSClass(clazz) && !isSkipClass(clazz)
                                && !java.lang.Exception.class.isAssignableFrom(clazz)) {

                            // Ensure that all the referenced classes are loadable too
                            clazz.getDeclaredMethods();
                            clazz.getDeclaredFields();

                            if (log.isDebugEnabled()) {
                                log.debug("Adding class: " + file);
                            }
                            classes.add(clazz);

                            // REVIEW:
                            // Support of RPC list (and possibly other scenarios) requires that the array classes should also be present.
                            // This is a hack until we can determine how to get this information.

                            // The arrayName and loadable name are different.  Get the loadable
                            // name, load the array class, and add it to our list
                            //className += "[]";
                            //String loadableName = ClassUtils.getLoadableClassName(className);

                            //Class aClazz = Class.forName(loadableName, false, Thread.currentThread().getContextClassLoader());
                        }
                        //Catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                        //does not extend Exception
                    } catch (Throwable e) {
                        if (log.isDebugEnabled()) {
                            log.debug("Tried to load class " + className
                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                            log.debug("  The reason that class could not be loaded:" + e.toString());
                            log.trace(JavaUtils.stackToString(e));
                        }
                    }

                }
            }
        }
    }

    return classes;
}

From source file:com.fun.rrs.common.excel.ExportExcel.java

/**
 * // www . j a  v  a2 s .c om
 * @param title ?
 * @param cls annotation.ExportField?
 * @param type 1:?2?
 * @param groups 
 */
public ExportExcel(String title, Class<?> cls, int type, int... groups) {
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == type)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == type)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    // Initialize
    List<String> headerList = new ArrayList<String>();
    for (Object[] os : annotationList) {
        String t = ((ExcelField) os[0]).title();
        // 
        if (type == 1) {
            String[] ss = StringUtils.split(t, "**", 2);
            if (ss.length == 2) {
                t = ss[0];
            }
        }
        headerList.add(t);
    }
    initialize(title, headerList);
}

From source file:com.topsem.common.io.excel.ExportExcel.java

/**
 * //from   ww w. ja  v  a  2s  .co  m
 * @param title ?
 * @param cls annotation.ExportField?
 * @param type 1:?2?
 * @param groups 
 */
public ExportExcel(String title, Class<?> cls, int type, int... groups) {
    // Get annotation field
    Field[] fs = cls.getDeclaredFields();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == type)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == type)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    // Initialize
    List<String> headerList = Lists.newArrayList();
    for (Object[] os : annotationList) {
        String t = ((ExcelField) os[0]).title();
        // 
        if (type == 1) {
            String[] ss = StringUtils.split(t, "**", 2);
            if (ss.length == 2) {
                t = ss[0];
            }
        }
        headerList.add(t);
    }
    initialize(title, headerList);
}

From source file:ClassFigure.java

public ClassFigure(Class cls) {
    setLayoutManager(new ToolbarLayout());
    setBorder(new LineBorder(ColorConstants.black));
    setBackgroundColor(ColorConstants.yellow);
    setOpaque(true);// w  w  w. ja va2 s .co  m

    for (int i = 0; i < keys.length; i++)
        registry.put(keys[i], ImageDescriptor.createFromFile(null, "icons/java/" + keys[i] + ".gif"));

    Label title = new Label(cls.getName(), registry.get(KEY_CLASS));
    add(title);
    add(fieldBox);
    add(methodBox);

    // fields.
    Field[] fields = cls.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        Image image = null;
        if (Modifier.isPublic(field.getModifiers())) {
            image = registry.get(KEY_FIELD_PUBLIC);
        } else if (Modifier.isProtected(field.getModifiers())) {
            image = registry.get(KEY_FIELD_PROTECTED);
        } else if (Modifier.isPrivate(field.getModifiers())) {
            image = registry.get(KEY_FIELD_PRIVATE);
        } else {
            image = registry.get(KEY_FIELD_DEFAULT);
        }
        fieldBox.add(new Label(fields[i].getName(), image));
    }

    // fields.
    Method[] methods = cls.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        Image image = null;
        if (Modifier.isPublic(method.getModifiers())) {
            image = registry.get(KEY_METHOD_PUBLIC);
        } else if (Modifier.isProtected(method.getModifiers())) {
            image = registry.get(KEY_METHOD_PROTECTED);
        } else if (Modifier.isPrivate(method.getModifiers())) {
            image = registry.get(KEY_METHOD_PRIVATE);
        } else {
            image = registry.get(KEY_METHOD_DEFAULT);
        }
        methodBox.add(new Label(methods[i].getName(), image));
    }

}