jeudi 21 février 2019

In "Reflection" and "Generic" how to type-cast from particular class and invokes a particular method?

This is the main class where the code started from:-

MainTest.java

class MainTest{
   public static void main(String... s) {
      Test1 test1 = new Test1();
      Test2 test2 = new Test2();
      Test3 test3 = new Test3();
      ------
      n-number of Test classes obect
      ------

     ReflectionTest reflectionTest = new ReflectionTest();
     reflectionTest.method1(test1);
     reflectionTest.method1(test2);
     reflectionTest.method1(test3);
     -------
     -------
     reflectionTest.method1(testn);
   }
}

And here Testn classes are same as below with the same method look like:- Testn.java classes

    class Test1 {
       void m1() {
          System.out.println("Hello Java");
       }
    }

class Test2 {
       void m1() {
          System.out.println("Hello Java");
       }
    }
--------
--------
class Testn {
       void m1() {
          System.out.println("Hello Java");
       }
    }

Here is the ReflectionTest.java class

class ReflectionTest {
  <T> void method1(T parameter) {
     Class c = parameter.getClass();
     Method[] methods = c.getMethods();

    for (int i = 0; i < methods.length; i++) {
        System.out.println(methods[i].getName());
    }

    //TODO
    ------Here I also want to execute the method from the reference class
    like:-
            /*
             * Object object = c.newInstance(); 
             * object.m1();
             */

  } 
}

How to call m1 method with the same class object which I pass from the parameter? Thanks in advance





Aucun commentaire:

Enregistrer un commentaire