原因
因为业务需求,接口类在moduleB中,实现类又要在主module中,因此想到用反射在moduleB 父类中创建子类,覆盖父类方法
代码例子
父类,作接口对外提供调用
public abstract class Parent{
private static Parent mParent;
public static Parent getInstatnce() {
if (mRhysdk == null) {
try {
@SuppressWarnings("unchecked")
Class<? extends Parent> classType = (Class<? extends Parent>)Class.forName("com.czg.Son");
mRhysdk = classType.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
return mRhysdk;
}
public abstract void onCreate(Activity activity);
public abstract void onStop(Activity activity);
public abstract void onDestroy(Activity activity);
}
子类,实现代码
public class Son extends Parent{
public Son () {
}
@Override
public void onCreate(Activity activity) {
Toast.makeText(activity,"创建成功",Toast.LENGTH_LONG);
}
@Override
public void onStop(Activity activity) {
}
@Override
public void onDestroy(Activity activity) {
}
}
项目中调用
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parent.getInstatnce().onCreate(this);
}
}