mardi 30 mai 2017

How to get the class type for which a collection object is created using reflection

I need your help to solve this, I have been trying to get an answer but didn't find one and I have very less time left to complete the assignment.

Code below :

 public class MainClass {
      @SuppressWarnings("unchecked")
      public static void main(String args[]) throws ClassNotFoundException {
           @SuppressWarnings("rawtypes")
           Class aClass = EmployeeDao.class;
           Method[] methods = aClass.getDeclaredMethods();

           @SuppressWarnings("rawtypes")
           Class returnType = null;
           for (Method method : methods) {
               if (!method.getReturnType().equals(Void.TYPE)) {
                  System.out.println(method.getName());

                  returnType = method.getReturnType();
                  if (returnType.isAssignableFrom(HashSet.class)) {
                      System.out.println("hash set");
                  }  
               }
           }
     }
 }

in the above code I am getting all the methods of a class and checking if its return type is HashSet and in that case I need to find out the type of object contained by the set object, for example the below method of EmployeeDao class:

public Set<Employee> findAllEmployees() {
     //some code here
}

I want to get the class object for Employee for the above method, I am not getting how to do it. The code above is static and I know in the above case, but this has to be done dynamically and above is only a demo code, at real time this program will get the class whose methods has to be accessed as an argument.





Aucun commentaire:

Enregistrer un commentaire