dimanche 28 novembre 2021

Getting access to class methods after creating an object using reflection

I get different class names (String) from external source e.g: reflection.Test1, reflection.Test2, reflection.OtherTest etc.

I need change these classes to new Objects so that I can use all the methods of a given object I am trying to create a dedicated method:

public static <T extends Base> T createObject(String nameOfClass) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<T> clazz = (Class<T>) Class.forName(nameOfClass);
        return clazz.getDeclaredConstructor().newInstance();
    }

But when I try to use it:

createObject("reflection.Test1").fillTest1();  //I want to use method fillTest1 from Test1.class
or:
createObject("reflection.Test2").fillTest2(); // //I want to use method fillTest1 from Test1.class

i get error in IntelliJ:

Cannot resolve method 'fillTest1' in 'Object'

How to make these methods visible? IntelliJ gives me access only to methods in Base.class: I can't see method in my Test1.class and Test2.class

Main.class:

public class Main {
    public static <T extends Base> T createObject(String nameOfClass) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<T> clazz = (Class<T>) Class.forName(nameOfClass);
        return clazz.getDeclaredConstructor().newInstance();
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // ... I get different class names from external source e.g: reflection.Test1, reflection.Test2, reflection.OtherTest etc.
        createObject("reflection.Test2").fillTest1(); //error :(
    }
}

Test1.class:

package reflection;

public class Test1 extends Base{
    private String name;

    public void fillTest1(String name){
        this.name = name;
    }

}

Test2.class:

package reflection;

public class Test2 extends Base{
    private String test2;

    public void fillTest2(String test2){
        this.test2 = test2;
    } }

Base Class:

package reflection;

public class Base {
    public void setBase(){
        System.out.println("Base method");
    }
}




Aucun commentaire:

Enregistrer un commentaire