Java反射-在方法之前查找Arguments和注释



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

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);
        }
    }

请帮我解决这个问题。

向致以最诚挚的问候

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);
...

以下代码段获取给定类(示例中为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);
        }
    }
}

相关内容

  • 没有找到相关文章