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.aware.Aware.java

/**
 * Given a plugin's package name, fetch the context card for reuse.
 * @param context: application context//www.j av a2 s.c  o  m
 * @param package_name: plugin's package name
 * @return View for reuse (instance of LinearLayout)
 */
public static View getContextCard(final Context context, final String package_name) {

    if (!isClassAvailable(context, package_name, "ContextCard")) {
        return null;
    }

    String ui_class = package_name + ".ContextCard";
    LinearLayout card = new LinearLayout(context);
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    card.setLayoutParams(params);
    card.setOrientation(LinearLayout.VERTICAL);

    try {
        Context packageContext = context.createPackageContext(package_name,
                Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);

        Class<?> fragment_loader = packageContext.getClassLoader().loadClass(ui_class);
        Object fragment = fragment_loader.newInstance();
        Method[] allMethods = fragment_loader.getDeclaredMethods();
        Method m = null;
        for (Method mItem : allMethods) {
            String mName = mItem.getName();
            if (mName.contains("getContextCard")) {
                mItem.setAccessible(true);
                m = mItem;
                break;
            }
        }

        View ui = (View) m.invoke(fragment, packageContext);
        if (ui != null) {
            //Check if plugin has settings. If it does, tapping the card shows the settings
            if (isClassAvailable(context, package_name, "Settings")) {
                ui.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent open_settings = new Intent();
                        open_settings.setClassName(package_name, package_name + ".Settings");
                        open_settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(open_settings);
                    }
                });
            }

            //Set card look-n-feel
            ui.setBackgroundColor(Color.WHITE);
            ui.setPadding(20, 20, 20, 20);
            card.addView(ui);

            LinearLayout shadow = new LinearLayout(context);
            LayoutParams params_shadow = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            params_shadow.setMargins(0, 0, 0, 10);
            shadow.setBackgroundColor(context.getResources().getColor(R.color.card_shadow));
            shadow.setMinimumHeight(5);
            shadow.setLayoutParams(params_shadow);
            card.addView(shadow);

            return card;
        } else {
            return null;
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:ClassReader.java

protected final Member resolveMethod(int index)
        throws IOException, ClassNotFoundException, NoSuchMethodException {
    int oldPos = pos;
    try {// ww w . jav  a  2 s .c om
        Member m = (Member) cpool[index];
        if (m == null) {
            pos = cpoolIndex[index];
            Class owner = resolveClass(readShort());
            NameAndType nt = resolveNameAndType(readShort());
            String signature = nt.name + nt.type;
            if ("<init>".equals(nt.name)) {
                Constructor[] ctors = owner.getConstructors();
                for (int i = 0; i < ctors.length; i++) {
                    String sig = getSignature(ctors[i], ctors[i].getParameterTypes());
                    if (sig.equals(signature)) {
                        cpool[index] = ctors[i];
                        m = ctors[i];
                        return m;
                    }
                }
            } else {
                Method[] methods = owner.getDeclaredMethods();
                for (int i = 0; i < methods.length; i++) {
                    String sig = getSignature(methods[i], methods[i].getParameterTypes());
                    if (sig.equals(signature)) {
                        cpool[index] = methods[i];
                        m = methods[i];
                        return m;
                    }
                }
            }
            throw new NoSuchMethodException(signature);
        }
        return m;
    } finally {
        pos = oldPos;
    }

}

From source file:net.ymate.platform.validation.ValidationMeta.java

public ValidationMeta(IValidation validation, Class<?> targetClass) {
    __validation = validation;//w  w  w  .ja  va2  s.c  om
    // ?targetClass@Validation?????
    Validation _classValidation = targetClass.getAnnotation(Validation.class);
    if (_classValidation != null) {
        __mode = _classValidation.mode();
    } else {
        __mode = Validation.MODE.NORMAL;
    }
    __targetClass = targetClass;
    __fields = new LinkedHashMap<String, Annotation[]>();
    __labels = new LinkedHashMap<String, String>();
    __methodLabels = new LinkedHashMap<Method, Map<String, String>>();
    __methods = new LinkedHashMap<Method, Validation>();
    __methodParams = new LinkedHashMap<Method, Map<String, Annotation[]>>();

    // ?targetClassField?
    __fields.putAll(__doGetMetaFromFields(null, targetClass, __labels));

    // ?targetClassMethod
    for (Method _method : targetClass.getDeclaredMethods()) {
        Map<String, String> _paramLabels = new LinkedHashMap<String, String>();
        __methodLabels.put(_method, _paramLabels);
        // ??@Validation
        Validation _methodValidation = _method.getAnnotation(Validation.class);
        if (_methodValidation != null) {
            __methods.put(_method, _methodValidation);
        }
        // ????
        Map<String, Annotation[]> _paramAnnos = new LinkedHashMap<String, Annotation[]>();
        String[] _paramNames = ClassUtils.getMethodParamNames(_method);
        Annotation[][] _params = _method.getParameterAnnotations();
        for (int _idx = 0; _idx < _paramNames.length; _idx++) {
            List<Annotation> _tmpAnnoList = new ArrayList<Annotation>();
            String _paramName = _paramNames[_idx];
            // ?????
            for (Annotation _vField : _params[_idx]) {
                if (_vField instanceof VField) {
                    VField _vF = (VField) _vField;
                    if (StringUtils.isNotBlank(_vF.name())) {
                        _paramName = ((VField) _vField).name();
                    }
                    if (StringUtils.isNotBlank(_vF.label())) {
                        _paramLabels.put(_paramName, _vF.label());
                    }
                    break;
                }
            }
            for (Annotation _annotation : _params[_idx]) {
                if (__doIsValid(_annotation)) {
                    _tmpAnnoList.add(_annotation);
                } else if (_annotation instanceof VModel) {
                    // ?@VModel
                    _paramAnnos.putAll(
                            __doGetMetaFromFields(_paramName, _method.getParameterTypes()[_idx], _paramLabels));
                }
            }
            if (!_tmpAnnoList.isEmpty()) {
                _paramAnnos.put(_paramName, _tmpAnnoList.toArray(new Annotation[_tmpAnnoList.size()]));
            }
        }
        if (!_paramAnnos.isEmpty()) {
            __methodParams.put(_method, _paramAnnos);
        }
    }
}

From source file:org.brekka.stillingar.spring.bpp.ConfigurationBeanPostProcessor.java

/**
 * Prepare the {@link ValueDefinitionGroup} for the specified bean.
 * //from  ww w.ja  va  2  s  . c  o  m
 * @param beanName
 *            the name of the bean used in log messages etc.
 * @param target
 *            the bean being configured
 * @return the value definition group
 */
protected ValueDefinitionGroup prepareValueGroup(String beanName, Object target) {
    List<ValueDefinition<?, ?>> valueList = new ArrayList<ValueDefinition<?, ?>>();

    Class<? extends Object> beanClass = target.getClass();
    if (target instanceof OnceOnlyTypeHolder) {
        /*
         * The target bean is not available, just the type.
         */
        beanClass = ((OnceOnlyTypeHolder) target).get();
    }

    Class<?> inpectClass = beanClass;
    while (inpectClass != null) {
        Field[] declaredFields = inpectClass.getDeclaredFields();
        for (Field field : declaredFields) {
            processField(field, valueList, target);
        }
        inpectClass = inpectClass.getSuperclass();
    }

    PostUpdateChangeListener beanChangeListener = null;

    Method[] declaredMethods = beanClass.getDeclaredMethods();
    Arrays.sort(declaredMethods, new Comparator<Method>() {
        @Override
        public int compare(Method o1, Method o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    for (Method method : declaredMethods) {
        Configured configured = method.getAnnotation(Configured.class);

        ConfigurationListener configurationListener = method.getAnnotation(ConfigurationListener.class);
        if (configurationListener != null) {
            if (beanChangeListener != null) {
                throw new ConfigurationException(format(
                        "Unable to create a configuration listener for the method '%s' on the bean '%s' (type '%s') "
                                + "as it already contains a configuration listener on the method '%s'",
                        method.getName(), beanName, beanClass.getName(),
                        beanChangeListener.getMethod().getName()));
            }
            beanChangeListener = processListenerMethod(method, valueList, target);

        } else if (configured != null) {
            processSetterMethod(configured, method, valueList, target);
        }
    }
    ValueDefinitionGroup group = new ValueDefinitionGroup(beanName, valueList, beanChangeListener, target);
    return group;
}

From source file:com.opensymphony.xwork2.util.finder.ClassFinder.java

public ClassFinder(List<Class> classes) {
    this.classLoaderInterface = null;
    List<Info> infos = new ArrayList<Info>();
    List<Package> packages = new ArrayList<Package>();
    for (Class clazz : classes) {

        Package aPackage = clazz.getPackage();
        if (aPackage != null && !packages.contains(aPackage)) {
            infos.add(new PackageInfo(aPackage));
            packages.add(aPackage);/*w w  w  .  java2  s. c o m*/
        }

        ClassInfo classInfo = new ClassInfo(clazz);
        infos.add(classInfo);
        classInfos.put(classInfo.getName(), classInfo);
        for (Method method : clazz.getDeclaredMethods()) {
            infos.add(new MethodInfo(classInfo, method));
        }

        for (Constructor constructor : clazz.getConstructors()) {
            infos.add(new MethodInfo(classInfo, constructor));
        }

        for (Field field : clazz.getDeclaredFields()) {
            infos.add(new FieldInfo(classInfo, field));
        }
    }

    for (Info info : infos) {
        for (AnnotationInfo annotation : info.getAnnotations()) {
            List<Info> annotationInfos = getAnnotationInfos(annotation.getName());
            annotationInfos.add(info);
        }
    }
}

From source file:org.apache.sling.models.impl.ModelAdapterFactory.java

private void invokePostConstruct(Object object) throws InvocationTargetException, IllegalAccessException {
    Class<?> clazz = object.getClass();
    List<Method> postConstructMethods = new ArrayList<Method>();
    while (clazz != null) {
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(PostConstruct.class)) {
                addMethodIfNotOverriden(postConstructMethods, method);
            }/* ww  w . jav  a2 s .c o  m*/
        }
        clazz = clazz.getSuperclass();
    }
    Collections.reverse(postConstructMethods);
    for (Method method : postConstructMethods) {
        boolean accessible = method.isAccessible();
        try {
            if (!accessible) {
                method.setAccessible(true);
            }
            method.invoke(object);
        } finally {
            if (!accessible) {
                method.setAccessible(false);
            }
        }
    }
}

From source file:org.castor.jaxb.reflection.FieldAnnotationProcessingServiceTest.java

@Test
public final void testWithXmlElements() {
    Class<WithXmlElements> clazz = WithXmlElements.class;
    Assert.assertFalse(clazz.isEnum());//  ww  w.java  2 s. c o  m
    Assert.assertNotNull(fieldAnnotationProcessingService);
    Field[] fields = clazz.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        JaxbFieldNature fi = new JaxbFieldNature(new FieldInfo(field.getName()));
        fieldAnnotationProcessingService.processAnnotations(fi, field.getAnnotations());
        if ("anythingInAList".equals(field.getName())) {
            Assert.assertTrue(fi.hasXmlElements());
            //                List<XmlElement> xmlElements = fi.getXmlElements();
            //                Assert.assertNotNull(xmlElements);

        }
    }
    Method[] methods = clazz.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        JaxbFieldNature fi = new JaxbFieldNature(new FieldInfo(method.getName()));
        fieldAnnotationProcessingService.processAnnotations(fi, method.getAnnotations());
    }
}

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

@SuppressWarnings("WeakerAccess")
public JsonApiResourceDeserializer(String apiType, Class<T> klass) {
    this.klass = klass;
    this.apiType = apiType;

    for (Field field : FieldUtils.getAllFieldsList(klass)) {
        ResourceId resourceId = field.getAnnotation(ResourceId.class);
        if (resourceId != null) {
            validateResourceId(field.getType());
            idSetter = new FieldSetter(field);
        }// w  w w  .  j  av  a2s. c om
        Relationship relationship = field.getAnnotation(Relationship.class);
        if (relationship != null) {
            String name = validateRelationship(field.getType(), relationship);
            relationshipSetters.put(name, new FieldSetter(field));
        }
        ResourceLink resourceLink = field.getAnnotation(ResourceLink.class);
        if (resourceLink != null) {
            String name = validateResourceLink(field.getType(), resourceLink);
            linkSetters.put(name, new FieldSetter(field));
        }
    }

    for (Method method : klass.getDeclaredMethods()) {
        ResourceId resourceId = method.getAnnotation(ResourceId.class);
        if (resourceId != null) {
            validateMethodParameters(ResourceId.class, method);
            idSetter = new MethodSetter(method);
        }
        Relationship relationship = method.getAnnotation(Relationship.class);
        if (relationship != null) {
            Class<?> parameter = validateMethodParameters(Relationship.class, method);
            String name = validateRelationship(parameter, relationship);
            relationshipSetters.put(name, new MethodSetter(method));
        }
        ResourceLink resourceLink = method.getAnnotation(ResourceLink.class);
        if (resourceLink != null) {
            Class<?> parameter = validateMethodParameters(ResourceLink.class, method);
            String name = validateResourceLink(parameter, resourceLink);
            linkSetters.put(name, new MethodSetter(method));
        }
    }
    if (idSetter == null) {
        throw new IllegalStateException("Must provide a ResourceId for " + klass);
    }
}

From source file:com.github.reinert.jjschema.HyperSchemaGeneratorV4.java

private <T> ObjectNode generateHyperSchemaFromResource(Class<T> type) throws TypeException {
    ObjectNode schema = null;/*w  ww .  jav a 2 s  .c  om*/

    Annotation[] ans = type.getAnnotations();
    boolean hasPath = false;
    for (Annotation a : ans) {
        if (a instanceof Path) {
            hasPath = true;
            Path p = (Path) a;
            if (schema == null) {
                schema = jsonSchemaGenerator.createInstance();
            }
            schema.put("pathStart", p.value());
        }
        if (a instanceof Produces) {
            Produces p = (Produces) a;
            if (schema == null) {
                schema = jsonSchemaGenerator.createInstance();
            }
            schema.put(MEDIA_TYPE, p.value()[0]);
        }
    }
    if (!hasPath) {
        throw new RuntimeException("Invalid Resource class. Must use Path annotation.");
    }

    ArrayNode links = schema.putArray("links");

    for (Method method : type.getDeclaredMethods()) {
        try {
            ObjectNode link = generateLink(method);
            if ("GET".equals(link.get("method").asText()) && "#".equals(link.get("href").asText())) {
                jsonSchemaGenerator.mergeSchema(schema, (ObjectNode) link.get("targetSchema"), true);
            } else {
                links.add(link);
            }
        } catch (InvalidLinkMethod e) {
            e.printStackTrace();
        }
    }

    return schema;
}

From source file:com.taobao.ad.easyschedule.security.ActionSecurityBean.java

/**
 * ??BO?Annotation??Annotation?/* w  w  w.  ja va2s  . c o m*/
 */
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    String[] beanNames = applicationContext.getBeanDefinitionNames();
    if (beanNames == null || beanNames.length == 0) {
        System.err.println(
                "Warning: seems there are no Spring Beans defined, please double check..................");
        return;
    }
    for (String name : beanNames) {
        if (!name.endsWith("Action")) {
            continue;
        }
        Class<?> c = AopUtils.getTargetClass(applicationContext.getBean(name));
        Object bean = applicationContext.getBean(name);

        while (Proxy.isProxyClass(c) && (bean instanceof Advised)) {
            try {
                bean = ((Advised) bean).getTargetSource();
                bean = ((TargetSource) bean).getTarget();
                c = bean.getClass();
            } catch (Exception e) {
                throw new IllegalStateException("Can't initialize SecurityBean, due to:" + e.getMessage());
            }
        }
        long moduleIdDefinedInInterface = -1;
        ActionSecurity moduleAnno = AnnotationUtils.findAnnotation(c, ActionSecurity.class);
        if (moduleAnno != null) {
            moduleIdDefinedInInterface = moduleAnno.module();
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            ActionSecurity methodAnno = AnnotationUtils.findAnnotation(method, ActionSecurity.class);
            if (methodAnno != null || moduleIdDefinedInInterface != -1) {
                if (methodAnno == null) {
                    methodAnno = moduleAnno; // use interface annotation
                }
                long module = methodAnno.module() == 0 ? moduleIdDefinedInInterface : methodAnno.module();
                Module myModule = moduleIndex.get(module);
                if (myModule == null) {
                    throw new IllegalArgumentException(
                            "Found invalid module id:" + module + " in method annotation:" + method
                                    + " valid module ids are: " + moduleIndex.keySet());
                }
                if (methodAnno.enable()) {
                    myModule.addOperation(method, methodAnno, methodIndex);
                }
            }
        }
    }
    System.out.println("[ActionSecurityBean] Total " + methodIndex.size() + " methods are secured!");
}