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.github.gekoh.yagen.ddl.TableConfig.java

public void scanEntityClass(Class entityClass, boolean selectiveRendering) {
    Class annClass = entityClass;
    while (annClass != null) {
        for (Annotation annotation : annClass.getAnnotations()) {
            if (COLLECT_ANNOTATIONS.contains(annotation.annotationType())
                    && !annotations.contains(annotation)) {
                putTableAnnotation(annotation);
            }// w w  w. ja  v  a  2 s.com
        }
        if (baseClass.equals(getClassOfTableAnnotation(annClass))) {
            annClass = annClass.getSuperclass();
        } else {
            break;
        }
    }

    com.github.gekoh.yagen.api.Table addTblInfo = (com.github.gekoh.yagen.api.Table) entityClass
            .getAnnotation(com.github.gekoh.yagen.api.Table.class);
    if (addTblInfo != null && addTblInfo.additionalSequences().length > 0) {
        sequences.addAll(Arrays.asList(addTblInfo.additionalSequences()));
    }

    processTypeAnnotations(entityClass, selectiveRendering);

    addI18NInfo(entityClass.getDeclaredFields());
    addI18NInfo(entityClass.getDeclaredMethods());

    gatherPkColumn(entityClass);
    gatherEnumCheckConstraints(entityClass);
    gatherCascade(entityClass);
    gatherDeferrable(entityClass);
}

From source file:org.imsglobal.lti.toolProvider.ToolProvider.java

private boolean doCallback(String method) {

    String callback = method;//from w  w  w.  ja v  a  2s  .  c om
    Boolean retVal = null;
    if (callback == null) {
        callback = getMessageType();
    }
    Class<? extends ToolProvider> clazz = this.getClass();
    boolean methodExists = false;
    for (Method m : clazz.getDeclaredMethods()) {
        if (m.getName().equals(callback)) {
            methodExists = true;
            try {
                retVal = (Boolean) m.invoke(this);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } //returns a boolean
        }
    }
    if (!methodExists) { //didn"t find the method in declared methods
        if (StringUtils.isNotEmpty(method)) {
            reason = "Message type not supported: " + getMessageType();
            retVal = false;
        }
    }
    if (retVal && (getMessageType().equals("ToolProxyRegistrationRequest"))) {
        consumer.save();
    }

    return retVal;

}

From source file:cn.orignzmn.shopkepper.common.utils.excel.ImportExcel.java

/**
 * ??/*from  w w  w  .j av a2s  . c  om*/
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, Map<String, Object> inportInfo, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    ExcelSheet esarr = cls.getAnnotation(ExcelSheet.class);
    String annTitle = "";
    if (esarr == null)
        return Lists.newArrayList();
    annTitle = esarr.value();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            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() == 2)) {
            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()));
        };
    });
    //log.debug("Import column count:"+annotationList.size());
    // Get excel data
    List<E> dataList = Lists.newArrayList();
    //???
    if (!"".equals(annTitle)) {
        String title = StringUtils.trim(this.getCellValue(this.getRow(0), 0).toString());
        if (!annTitle.equals(title)) {
            inportInfo.put("success", false);
            inportInfo.put("message", "??");
            return Lists.newArrayList();
        }
    }
    for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
        E e = (E) cls.newInstance();
        int column = 0;
        Row row = this.getRow(i);

        StringBuilder sb = new StringBuilder();
        for (Object[] os : annotationList) {
            Object val = this.getCellValue(row, column++);
            if (val != null) {
                ExcelField ef = (ExcelField) os[0];
                // If is dict type, get dict value
                //               if (StringUtils.isNotBlank(ef.dictType())){
                //                  val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
                //                  //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
                //               }
                // Get param type and type cast
                Class<?> valType = Class.class;
                if (os[1] instanceof Field) {
                    valType = ((Field) os[1]).getType();
                } else if (os[1] instanceof Method) {
                    Method method = ((Method) os[1]);
                    if ("get".equals(method.getName().substring(0, 3))) {
                        valType = method.getReturnType();
                    } else if ("set".equals(method.getName().substring(0, 3))) {
                        valType = ((Method) os[1]).getParameterTypes()[0];
                    }
                }
                //log.debug("Import value type: ["+i+","+column+"] " + valType);
                try {
                    if (valType == String.class) {
                        String s = String.valueOf(val.toString());
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            val = String.valueOf(val.toString());
                        }
                    } else if (valType == Integer.class) {
                        val = Double.valueOf(val.toString()).intValue();
                    } else if (valType == Long.class) {
                        val = Double.valueOf(val.toString()).longValue();
                    } else if (valType == Double.class) {
                        val = Double.valueOf(val.toString());
                    } else if (valType == Float.class) {
                        val = Float.valueOf(val.toString());
                    } else if (valType == Date.class) {
                        val = DateUtil.getJavaDate((Double) val);
                    } else {
                        if (ef.fieldType() != Class.class) {
                            val = ef.fieldType().getMethod("getValue", String.class).invoke(null,
                                    val.toString());
                        } else {
                            val = Class
                                    .forName(this.getClass().getName().replaceAll(
                                            this.getClass().getSimpleName(),
                                            "fieldtype." + valType.getSimpleName() + "Type"))
                                    .getMethod("getValue", String.class).invoke(null, val.toString());
                        }
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                if (os[1] instanceof Field) {
                    Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
                } else if (os[1] instanceof Method) {
                    String mthodName = ((Method) os[1]).getName();
                    if ("get".equals(mthodName.substring(0, 3))) {
                        mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
                    }
                    Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val });
                }
            }
            sb.append(val + ", ");
        }
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}

From source file:com.jskaleel.xml.JSONObject.java

private void populateMap(Object bean) {
    Class klass = bean.getClass();

    // If klass is a System class then set includeSuperClass to false.

    boolean includeSuperClass = klass.getClassLoader() != null;

    Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i += 1) {
        try {/*from  w  ww.ja  v a2  s .  com*/
            Method method = methods[i];
            if (Modifier.isPublic(method.getModifiers())) {
                String name = method.getName();
                String key = "";
                if (name.startsWith("get")) {
                    if ("getClass".equals(name) || "getDeclaringClass".equals(name)) {
                        key = "";
                    } else {
                        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) {
                        this.map.put(key, wrap(result));
                    }
                }
            }
        } catch (Exception ignore) {
        }
    }
}

From source file:com.lidroid.xutils.ViewUtils.java

@SuppressWarnings("ConstantConditions")
private static void injectObject(Object handler, ViewFinder finder) {

    Class<?> handlerType = handler.getClass();

    // inject ContentView
    ContentView contentView = handlerType.getAnnotation(ContentView.class);
    if (contentView != null) {
        try {//from   w  w  w.  j a v  a 2s .  c  o  m
            Method setContentViewMethod = handlerType.getMethod("setContentView", int.class);
            setContentViewMethod.invoke(handler, contentView.value());
        } catch (Throwable e) {
            LogUtils.e(e.getMessage(), e);
        }
    }

    // inject view
    Field[] fields = handlerType.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {
            ViewInject viewInject = field.getAnnotation(ViewInject.class);
            if (viewInject != null) {
                try {
                    View view = finder.findViewById(viewInject.value(), viewInject.parentId());
                    if (view != null) {
                        field.setAccessible(true);
                        field.set(handler, view);
                    }
                } catch (Throwable e) {
                    LogUtils.e(e.getMessage(), e);
                }
            } else {
                ResInject resInject = field.getAnnotation(ResInject.class);
                if (resInject != null) {
                    try {
                        Object res = ResLoader.loadRes(resInject.type(), finder.getContext(), resInject.id());
                        if (res != null) {
                            field.setAccessible(true);
                            field.set(handler, res);
                        }
                    } catch (Throwable e) {
                        LogUtils.e(e.getMessage(), e);
                    }
                } else {
                    PreferenceInject preferenceInject = field.getAnnotation(PreferenceInject.class);
                    if (preferenceInject != null) {
                        try {
                            Preference preference = finder.findPreference(preferenceInject.value());
                            if (preference != null) {
                                field.setAccessible(true);
                                field.set(handler, preference);
                            }
                        } catch (Throwable e) {
                            LogUtils.e(e.getMessage(), e);
                        }
                    }
                }
            }
        }
    }

    // inject event
    Method[] methods = handlerType.getDeclaredMethods();
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {
            Annotation[] annotations = method.getDeclaredAnnotations();
            if (annotations != null && annotations.length > 0) {
                for (Annotation annotation : annotations) {
                    Class<?> annType = annotation.annotationType();
                    if (annType.getAnnotation(EventBase.class) != null) {
                        method.setAccessible(true);
                        try {
                            // ProGuard-keep class * extends java.lang.annotation.Annotation { *; }
                            Method valueMethod = annType.getDeclaredMethod("value");
                            Method parentIdMethod = null;
                            try {
                                parentIdMethod = annType.getDeclaredMethod("parentId");
                            } catch (Throwable e) {
                            }
                            Object values = valueMethod.invoke(annotation);
                            Object parentIds = parentIdMethod == null ? null
                                    : parentIdMethod.invoke(annotation);
                            int parentIdsLen = parentIds == null ? 0 : Array.getLength(parentIds);
                            int len = Array.getLength(values);
                            for (int i = 0; i < len; i++) {
                                ViewInjectInfo info = new ViewInjectInfo();
                                info.value = Array.get(values, i);
                                info.parentId = parentIdsLen > i ? (Integer) Array.get(parentIds, i) : 0;
                                EventListenerManager.addEventMethod(finder, info, annotation, handler, method);
                            }
                        } catch (Throwable e) {
                            LogUtils.e(e.getMessage(), e);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.zhoukl.androidRDP.RdpUtils.RdpAnnotationUtil.java

@SuppressWarnings("ConstantConditions")
private static void injectObject(Object handler, ViewFinder finder) {

    Class<?> handlerType = handler.getClass();

    // inject ContentView
    ContentView contentView = handlerType.getAnnotation(ContentView.class);
    if (contentView != null) {
        try {/* w w w .  ja v  a  2  s  .co  m*/
            Method setContentViewMethod = handlerType.getMethod("setContentView", int.class);
            setContentViewMethod.invoke(handler, contentView.value());
        } catch (Throwable e) {
            //LogUtils.e(e.getMessage(), e);
        }
    }

    // inject view
    Field[] fields = handlerType.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {
            ViewInject viewInject = field.getAnnotation(ViewInject.class);
            if (viewInject != null) {
                try {
                    View view = finder.findViewById(viewInject.value(), viewInject.parentId());
                    if (view != null) {
                        field.setAccessible(true);
                        field.set(handler, view);
                    }
                } catch (Throwable e) {
                    //LogUtils.e(e.getMessage(), e);
                }
            } else {
                ResInject resInject = field.getAnnotation(ResInject.class);
                if (resInject != null) {
                    try {
                        Object res = ResLoader.loadRes(resInject.type(), finder.getContext(), resInject.id());
                        if (res != null) {
                            field.setAccessible(true);
                            field.set(handler, res);
                        }
                    } catch (Throwable e) {
                        //LogUtils.e(e.getMessage(), e);
                    }
                } else {
                    PreferenceInject preferenceInject = field.getAnnotation(PreferenceInject.class);
                    if (preferenceInject != null) {
                        try {
                            Preference preference = finder.findPreference(preferenceInject.value());
                            if (preference != null) {
                                field.setAccessible(true);
                                field.set(handler, preference);
                            }
                        } catch (Throwable e) {
                            //LogUtils.e(e.getMessage(), e);
                        }
                    }
                }
            }
        }
    }

    // inject event
    Method[] methods = handlerType.getDeclaredMethods();
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {
            Annotation[] annotations = method.getDeclaredAnnotations();
            if (annotations != null && annotations.length > 0) {
                for (Annotation annotation : annotations) {
                    Class<?> annType = annotation.annotationType();
                    if (annType.getAnnotation(EventBase.class) != null) {
                        method.setAccessible(true);
                        try {
                            // ProGuard-keep class * extends java.lang.annotation.Annotation { *; }
                            Method valueMethod = annType.getDeclaredMethod("value");
                            Method parentIdMethod = null;
                            try {
                                parentIdMethod = annType.getDeclaredMethod("parentId");
                            } catch (Throwable e) {
                            }
                            Object values = valueMethod.invoke(annotation);
                            Object parentIds = parentIdMethod == null ? null
                                    : parentIdMethod.invoke(annotation);
                            int parentIdsLen = parentIds == null ? 0 : Array.getLength(parentIds);
                            int len = Array.getLength(values);
                            for (int i = 0; i < len; i++) {
                                ViewInjectInfo info = new ViewInjectInfo();
                                info.value = Array.get(values, i);
                                info.parentId = parentIdsLen > i ? (Integer) Array.get(parentIds, i) : 0;
                                EventListenerManager.addEventMethod(finder, info, annotation, handler, method);
                            }
                        } catch (Throwable e) {
                            //LogUtils.e(e.getMessage(), e);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.agimatec.validation.jsr303.Jsr303MetaBeanFactory.java

/**
 * process class annotations, field and method annotations
 *
 * @throws IllegalAccessException//from w ww  . j  a v  a 2 s . co  m
 * @throws InvocationTargetException
 */
private void processClass(Class<?> beanClass, MetaBean metabean)
        throws IllegalAccessException, InvocationTargetException {
    if (!factoryContext.getFactory().getAnnotationIgnores().isIgnoreAnnotations(beanClass)) { // ignore on class level

        processAnnotations(null, beanClass, beanClass, null, new AppendValidationToMeta(metabean));

        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            MetaProperty metaProperty = metabean.getProperty(field.getName());
            // create a property for those fields for which there is not yet a MetaProperty
            if (!factoryContext.getFactory().getAnnotationIgnores().isIgnoreAnnotations(field)) {
                if (metaProperty == null) {
                    metaProperty = createMetaProperty(field.getName(), field.getType());
                    /*if (*/
                    processAnnotations(metaProperty, beanClass, field, new FieldAccess(field),
                            new AppendValidationToMeta(metaProperty));//) {
                    metabean.putProperty(metaProperty.getName(), metaProperty);
                    //}
                } else {
                    processAnnotations(metaProperty, beanClass, field, new FieldAccess(field),
                            new AppendValidationToMeta(metaProperty));
                }
            }
        }
        Method[] methods = beanClass.getDeclaredMethods();
        for (Method method : methods) {

            String propName = null;
            if (method.getParameterTypes().length == 0) {
                propName = MethodAccess.getPropertyName(method);
            }
            if (propName != null) {
                if (!factoryContext.getFactory().getAnnotationIgnores().isIgnoreAnnotations(method)) {
                    MetaProperty metaProperty = metabean.getProperty(propName);
                    // create a property for those methods for which there is not yet a MetaProperty
                    if (metaProperty == null) {
                        metaProperty = createMetaProperty(propName, method.getReturnType());
                        /*if (*/
                        processAnnotations(metaProperty, beanClass, method, new MethodAccess(propName, method),
                                new AppendValidationToMeta(metaProperty));//) {
                        metabean.putProperty(propName, metaProperty);
                        //}
                    } else {
                        processAnnotations(metaProperty, beanClass, method, new MethodAccess(propName, method),
                                new AppendValidationToMeta(metaProperty));
                    }
                }
            }
        }
    }
    addXmlConstraints(beanClass, metabean);
}

From source file:alice.tuprolog.lib.OOLibrary.java

/**
 * @author Roberta Calegari/*w ww  . ja  v  a 2  s.co m*/
 * 
 * Creates of a lambda object - not backtrackable case
 * @param interfaceName represent the name of the target interface i.e. 'java.util.function.Predicate<String>'
 * @param implementation contains the function implementation i.e. 's -> s.length()>4 '
 * @param id represent the identification_name of the created object function i.e. MyLambda
 * 
 * @throws JavaException, Exception
 */
@SuppressWarnings("unchecked")
public <T> boolean new_lambda_3(PTerm interfaceName, PTerm implementation, PTerm id)
        throws JavaException, Exception {
    try {
        counter++;
        String target_class = (interfaceName.toString()).substring(1, interfaceName.toString().length() - 1);
        String lambda_expression = (implementation.toString()).substring(1,
                implementation.toString().length() - 1);
        //following lines allow to delete escape char from received string
        target_class = org.apache.commons.lang3.StringEscapeUtils.unescapeJava(target_class);
        lambda_expression = org.apache.commons.lang3.StringEscapeUtils.unescapeJava(lambda_expression);

        Class<?> lambdaMetaFactory = alice.util.proxyGenerator.Generator.make(
                java.lang.ClassLoader.getSystemClassLoader(), "MyLambdaFactory" + counter,
                "public class MyLambdaFactory" + counter + " {\n" + "  public " + target_class
                        + " getFunction() {\n" + "       return " + lambda_expression + "; \n" + "  }\n"
                        + "}\n");

        Object myLambdaFactory = lambdaMetaFactory.newInstance();
        Class<?> myLambdaClass = myLambdaFactory.getClass();
        Method[] allMethods = myLambdaClass.getDeclaredMethods();
        T myLambdaInstance = null;
        for (Method m : allMethods) {
            String mname = m.getName();
            if (mname.startsWith("getFunction"))
                myLambdaInstance = (T) m.invoke(myLambdaFactory);
        }
        id = id.getTerm();
        if (bindDynamicObject(id, myLambdaInstance))
            return true;
        else
            throw new JavaException(new Exception());
    } catch (Exception ex) {
        throw new JavaException(ex);
    }
}

From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java

private List<String> getPropOrderUncached(Class<?> beanClass) {
    List<String> propOrder;

    // Superclass first!
    Class superclass = beanClass.getSuperclass();
    if (superclass == null || superclass.equals(Object.class)
            || superclass.getAnnotation(XmlType.class) == null) {
        propOrder = new ArrayList<>();
    } else {/*from   ww  w. j av a2s .  c o  m*/
        propOrder = new ArrayList<>(getPropOrder(superclass));
    }

    XmlType xmlType = beanClass.getAnnotation(XmlType.class);
    if (xmlType == null) {
        throw new IllegalArgumentException(
                "Cannot marshall " + beanClass + " it does not have @XmlType annotation");
    }

    String[] myPropOrder = xmlType.propOrder();
    for (String myProp : myPropOrder) {
        if (StringUtils.isNotBlank(myProp)) {
            // some properties starts with underscore..we don't want to serialize them with underscore, so remove it..
            if (myProp.startsWith("_")) {
                myProp = myProp.replace("_", "");
            }
            propOrder.add(myProp);
        }
    }

    Field[] fields = beanClass.getDeclaredFields();
    for (Field field : fields) {
        if (field.isAnnotationPresent(XmlAttribute.class)) {
            propOrder.add(field.getName());
        }
    }

    Method[] methods = beanClass.getDeclaredMethods();
    for (Method method : methods) {
        if (method.isAnnotationPresent(XmlAttribute.class)) {
            propOrder.add(getPropertyNameFromGetter(method.getName()));
        }
    }

    return propOrder;
}

From source file:com.ng.mats.psa.mt.paga.data.JSONObject.java

private void populateMap(Object bean) {
    Class<?> klass = bean.getClass();

    // If klass is a System class then set includeSuperClass to false.

    boolean includeSuperClass = klass.getClassLoader() != null;

    Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i += 1) {
        try {//from   ww  w.  j  a va 2s. com
            Method method = methods[i];
            if (Modifier.isPublic(method.getModifiers())) {
                String name = method.getName();
                String key = "";
                if (name.startsWith("get")) {
                    if ("getClass".equals(name) || "getDeclaringClass".equals(name)) {
                        key = "";
                    } else {
                        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) {
                        this.map.put(key, wrap(result));
                    }
                }
            }
        } catch (Exception ignore) {
        }
    }
}