2013-04-22 159 views
3

我能夠在給定包名稱時獲取類及其方法名稱。代碼如下:Java-Reflection - 在方法之前找到參數和註釋

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

請幫我解決這個問題。

問候

+1

請嘗試應用在[SSCCE](http://sscce.org/)概念中,只有很少的代碼行應足以描述您的請求。 – sp00m 2013-04-22 10:14:45

回答

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

太棒了,我現在能夠獲得註釋,如何獲取該方法及其類型的參數? – 2013-04-22 09:28:29

+0

http://stackoverflow.com/questions/7976827/how-to-get-parameters-annotation-in-java – Ralph 2013-04-22 09:29:25

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); 
     } 
    } 
} 
相關問題