Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic class loading with Java

I want to dynamically load a concrete class which implements an interface. Input: concrete class name.

I need to call a method in this concrete class, that is, I'll need to set:

MyInterface myclass = new concreteClassName();
myclass.function();

How can I achieve this?

like image 353
Shakes Avatar asked May 05 '26 11:05

Shakes


1 Answers

have a look at Class.forName(String)

    String str = "Test$B"; //your full class name here instead of Test$B
    A clazz = null; //change A to be your interface
    try { 
    clazz = (A)Class.forName(str).newInstance(); //change A to be your interface

    } catch (Exception e) { 
        //TODO: handle exceptions
        e.printStackTrace();
    }
    if (clazz != null)  {
        clazz.foo();
    }
like image 95
amit Avatar answered May 08 '26 01:05

amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!