[英]Load class at runtime and use static function ,enum etc (Reflection)?
是否有人在反思中有好手。 請提出解決方案。
我的任務范圍如下:
/ *具有靜態Enum變量的類* /
公共最終課程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);
}
}
下面的代碼應該工作。
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的對象的實例。 讓我知道這是否適合您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.