【问题标题】:Load class at runtime and use static function ,enum etc (Reflection)?在运行时加载类并使用静态函数、枚举等(反射)?
【发布时间】:2013-08-13 09:36:32
【问题描述】:

有没有人在反射方面做得很好。请提出解决方案。

我的任务范围如下:-

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


}

}

【问题讨论】:

标签: java android swing reflection


【解决方案1】:

以下代码应该可以工作。

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 的对象实例。让我知道这是否适合您。

【讨论】:

  • 嗨,Teja!感谢您的回答。但我需要将枚举值作为反射(MConfiguration.Myenum.ONE)。
  • 嗨拉娜!上面的代码应该可以工作 m1.invoke(c1.newInstance(), mContext, MConfiguration.Myenum.ONE, true, true); 如果 com.rog.lib.sec.timlib 需要一个枚举value 在当前情况下是一个字符串(字符串 url),那么请使用以下方法:Method m1 = c1.getDeclaredMethod("init", mContext.getClass(), String.class, boolean.class, boolean.班级); m1.invoke(c1.newInstance(), mContext, MConfiguration.Myenum.ONE.getourl(), true, true); 如果您不期望以上内容,请在此处详细说明您的要求。
猜你喜欢
  • 2017-10-01
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
  • 2017-08-17
  • 1970-01-01
相关资源
最近更新 更多