0

有没有人擅长反射。请提出解决方案。

我的任务范围如下:-

  1. 我必须在运行时上课
  2. 使用它的静态函数。
  3. 在前一个类静态函数中传递另一个运行时类(MConfiguration 类)的静态枚举变量。

/* 具有静态枚举变量的类 */

公共最终类 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;
    }

我坚持使用静态枚举变量。我怎样才能实现 [timlib.init(mContext, Myenum.REFERENCE, true, true); ] 通过反思。以下是我的实现。

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);


}

}

4

1 回答 1

0

以下代码应该可以工作。

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. 

 }

如果您使用参数构造函数覆盖了构造函数,则调用参数构造函数以获取要传递给方法 m1 的对象实例。让我知道这是否适合您。

于 2013-08-13T13:57:48.277 回答