简体   繁体   中英

Load class at runtime and use static function ,enum etc (Reflection)?

Is there anybody have good hands in Reflection. Please suggest solution.

Scope of my task is following :-

  1. I have to get a class at run time
  2. Use its static Function.
  3. Pass a static enum variables of another run time class (class MConfiguration) in previous class static Function.

/* Class which have static Enum variable */

public final class MConfiguration {

public static enum Myenum {

    ONE("https://abc.org"),

    TWO("https://pqrs.org");

    private String ourl;

    /***
     * Constructor.
     *
     * @param url Configuration URL for this environment.
     */
    private Env(final String url) {
        ourl = url;
    }

I have stuck to use static enum variable. How can i implement [ timlib.init(mContext, Myenum.REFERENCE, true, true); ] by REFLECTION. Following is my implementation.

public String TIIMLIB       = "com.rog.lib.sec.timlib";
public String TIMLIB_EVENT = "com.rog.lib.sec.timEvent";
public String TIMIB_ENUM   = "com.rog.lib.sec.MConfiguration.Myenum";


/**
 *  Initialise TimLib API.
 */
public void initTimLib(Context mContext)
{
//  timlib.init(mContext, Myenum.REFERENCE, true, true); // actual needs to implement at runtime.

   Class cl = Class.forName(TIIMLIB);


}

}

The following code should work.

public void initTimLib(Context mContext)
{
    //  timlib.init(mContext, Myenum.REFERENCE, true, true); // actual needs to implement at runtime.

       Class cl = Class.forName(TIIMLIB);

       Method m1 = c1.getDeclaredMethod("init", mContext.getClass(), MConfiguration.Myenum.class, boolean.class, boolean.class);

       m1.invoke(c1.newInstance(), mContext, MConfiguration.Myenum.ONE, true, true); // The method invocation is done on the c1 object constructed using default constructor. I assume that the default constructor or no-arg constructor is used in c1. 

 }

If you have overridden constructor with argument constructor, then invoke the argument constructor to get an instance of object to be passed to Method m1. Let me know if this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM