简体   繁体   English

Java-Reflection-Spring如何识别参数是用户定义对象还是基本类型

[英]Java-Reflection-Spring how to identify whether the parameter is user defined object or Primitive Type

I am able to find all the method and argument the method takes using reflection, following is the way i have done it : 我能够找到所有方法和使用反射的方法所采用的参数,以下是我的方法:

HexgenClassUtils hexgenClassUtils = new HexgenClassUtils();
        Class cls;


        try {
            List classNames = hexgenClassUtils.findMyTypes("com.hexgen.*");
            Iterator<Class> it = classNames.iterator();
            while(it.hasNext())
            {

                Class obj = it.next(); 
                System.out.println("Methods available in : "+obj.getName());
                System.out.println("===================================");
                //if(obj.getName().equals("com.hexgen.api.facade.HexgenWebAPI")){
                    cls = Class.forName(obj.getName());
                    Method[] method = cls.getDeclaredMethods();
                    int i=1;

                    for (Method method2 : method) {
                        PreAuthorize preAuthorizeAnnotation = method2.getAnnotation(PreAuthorize.class);
                        if(preAuthorizeAnnotation !=null){
                            System.out.println(+i+":Method Name : "+method2.getName());
                            RequestMapping methodRequestMappingAnnotation = method2.getAnnotation(RequestMapping.class);
                            //RequestMethod[] methods = methodRequestMappingAnnotation.method(); // to get the request method type
                            mappingValues = methodRequestMappingAnnotation.value(); // to get the url value
                            System.out.println("URL Value : "+mappingValues[0]);
                            Class[] parameterTypes = method2.getParameterTypes();
                            for (Class class1 : parameterTypes) {
                                System.out.println("Parameter Type : "+class1.getName());
                            }
                            i++;
                        }

                    }
                //}

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

this is the utility class i use : 这是我使用的实用程序类:

package com.hexgen.tools;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.SystemPropertyUtils;

public class HexgenClassUtils {
    @SuppressWarnings({ "rawtypes"})
    public List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException
    {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

        List<Class> candidates = new ArrayList<Class>();
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                                   resolveBasePackage(basePackage) + "/" + "**/*.class";
        Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        for (Resource resource : resources) {
            if (resource.isReadable()) {
                MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                if (isCandidate(metadataReader)) {
                    candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
                }
            }
        }
        return candidates;
    }
    public String resolveBasePackage(String basePackage) {
        return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException
    {
        try {
            Class c = Class.forName(metadataReader.getClassMetadata().getClassName());
            if (!c.isInterface() && c.getAnnotation(Controller.class) != null) {
                return true;
            }
        }
        catch(Throwable e){
        }
        return false;
    }

}

and the output is : 输出为:

Methods available in : com.hexgen.api.facade.HexgenWebAPI
===================================
1:Method Name : createRequisition
URL Value : /trade/createrequisition
Parameter Type : [Lcom.hexgen.ro.request.CreateRequisitionRO;
Parameter Type : boolean
2:Method Name : createOrder
URL Value : /trade/createorder
Parameter Type : com.hexgen.ro.request.CreateOrderRO
Parameter Type : boolean
3:Method Name : RetrieveReportFields
URL Value : /reports/fields
Parameter Type : java.math.BigDecimal
4:Method Name : generateURL
URL Value : /reports/generateurl
Parameter Type : com.hexgen.ro.request.GenerateURLRO

for example : 例如 :

Parameter Type : [Lcom.hexgen.ro.request.CreateRequisitionRO; 参数类型:[Lcom.hexgen.ro.request.CreateRequisitionRO; Parameter Type : boolean 参数类型:布尔值

first one is user defined array of object and the second one is Primitive type

how to identify this through reflection also how to find the argument is array of objects or not. 如何通过反射来识别这一点,以及如何找到参数是否为对象数组。

Please clarify. 请澄清。

Best Regards 最好的祝福

You can use isArray() to check if the parameter type is an array or not. 您可以使用isArray()来检查参数类型是否为数组。

In your code it will be class1.isArray() 在您的代码中它将是class1.isArray()

Apart from primitives every thing is Object. 除了基元以外,所有事物都是对象。

I do not know a straight forward way but you can check if class1.getComponentType() does not match with Integer.TYPE, Double.TYPE, Boolean.TYPE, etc. ie all primitives then you have an Object. 我不知道一个简单的方法,但是您可以检查class1.getComponentType()是否与Integer.TYPE, Double.TYPE, Boolean.TYPE, etc.不匹配Integer.TYPE, Double.TYPE, Boolean.TYPE, etc.即所有原语都具有一个Object。

Class#isPrimitive()必须是您要寻找的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java反射〜设置原始类型的内部对象值 - Java Reflection ~ Set Inner Object Value Of A Primitive Type 如何处理反射中的原始类型 - how to deal with primitive type in reflection 如果type是primitive或type是object,则检入反射 - Check in reflection if type is primitive or type is object 如何使用 Java 反射将原始类型值分配给方法 args? - How to assign primitive type value to a method args using Java reflection? 如何在Java中测试对象是原始类型还是原始类型数组? - How to test if an object is primitive type or an array of primitive type in Java? 使用 @Aspect 类型 ZA2F2ED4F8EBC04ABBB4C21A2D9 中的 java 反射访问用户定义的 object state - Access user-defined object state using java reflection in @Aspect type class 在 Java 中,我如何查看 object 是否属于作为方法参数传递的正确类型? 特别是如果类型是原始类型? - In Java, how do I see if an object is of the right type to be passed as a method parameter? Especially if the type is a primitive? 如何从 Java 中的 object 获取原始类型? - how to get primitive type from object in Java? 如何判断原始类型是否被转换为Java中的对象? - How to tell if a primitive type was cast into an object in Java? Java Reflection with Object ...作为参数 - Java Reflection with Object… as a parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM