3

对于给定的包名称,我能够获取类及其方法名称。代码如下:

package com.hexgen.reflection;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import org.springframework.web.bind.annotation.RequestMapping;

import com.hexgen.ro.request.CreateRequisitionRO;
import com.hexgen.tools.HexgenClassUtils;

public class HexgenWebAPITest {


    @SuppressWarnings({ "rawtypes", "unchecked", "unused" })
    public static void main(String[] args) {
        HexgenWebAPITest test = new HexgenWebAPITest();
        HexgenClassUtils hexgenClassUtils = new HexgenClassUtils();
        String uri="";
        String[] mappingValues=null;
        HttpClientRequests httpRequest = new HttpClientRequests();
        Class parames = CreateRequisitionRO[].class;

        Class booleanVal;
        booleanVal = Boolean.TYPE;
        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("===================================");
                cls = Class.forName(obj.getName());
                Method[] method = cls.getMethods();
                int i=1;
                for (Method method2 : method) {
                    System.out.println(+i+":"+method2.getName());
                    i++;
                }
                System.out.println("===================================");
            }


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

    }

}

以下是我的 util 类:

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", "unused" })
    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;
    }

}

now how can i get the methods arguments and it's type through programmatically in spring ?

举个例子,如果我得到了类和下面的方法,那么应该能够得到@PreAuthorize,@RequestMapping,@ResponseBody,methodName and arguments it has like in this case it would be RequestBody CreateRequisitionRO[] request, @RequestHeader("validateOnly") boolean validateOnly and their TYPE

@PreAuthorize("isAuthenticated() and hasPermission(#request, 'CREATE_REQUISITION')")
    @RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
    public @ResponseBody
    void createRequisition(@RequestBody CreateRequisitionRO[] request,
            @RequestHeader("validateOnly") boolean validateOnly) {
        logger.debug("Starting createRequisition()...");
        for (int i = 0; i < request.length; i++) {
            CreateRequisitionRO requisitionRequest = request[i];

            // FIXME this has to be removed/moved
            requisitionRequest.setFundManager(requisitionRequest.getUserId());
            // FIXME might have to search using param level as well
            SystemDefault sysDefault = dbFuncs.references.systemDefault
                    .findByCompanyAndDivisionAndPortfolio(
                            userContext.getCompany(),
                            userContext.getDivision(),
                            requisitionRequest.getPortfolio());
            requisitionRequest.setCustodianN(sysDefault.getCustodianN());

            gateKeeper.route(requisitionRequest);
        }
    }

请帮我解决这个问题。

此致

4

2 回答 2

2
Class clazz = Demo.class

for(Method method : clazz.getMethods()) {
  for(Annotation annotation : method.getDeclaredAnnotations()) {
     System.out.println(annotation );
  }
}

如果您寻找特定的注释,那么您可以使用

RequestMapping requestMapping method.getAnnotation(RequestMapping.class);
System.out.println(requestMapping.values);
...
于 2013-04-22T09:19:06.313 回答
1

以下片段获取给定类的每个方法的每个注释的每个参数的属性(名称/类型/值)(YourType在示例中):

for (Method m : YourType.class.getDeclaredMethods()) {
    String methodName = m.getName();
    for (Annotation a : m.getDeclaredAnnotations()) {
        String annotationName = a.annotationType().getSimpleName();
        for (Method arg : a.annotationType().getDeclaredMethods()) {
            String argumentName = arg.getName();
            Class<?> argumentType = arg.getReturnType();
            Object argumentValue = arg.invoke(a);
        }
    }
}
于 2013-04-22T10:02:29.373 回答