如何使用反射动态创建一个扩展另一个动态类的类? [英] How can I create a class dynamically that extends another dynamic class using reflection?

查看:35
本文介绍了如何使用反射动态创建一个扩展另一个动态类的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样动态获取一个类:

I'm fetching a class dynamically like this:

Class<?> clazz = Class.forName("com.android.systemui.quicksettings.QuickSettingsTile");

我想创建另一个名为 DummyTile 的类,它扩展了我之前的类.它看起来像这样:

I'd like to create another class called DummyTile thats extends my previous class. It would have looked like this:

public class DummyTile extends QuickSettingsTile {

    public DummyTile(Context context, QuickSettingsController qsc) {
        super(context, qsc);
    }

    public void updateTile() {
        System.out.println("Hello");
    }

    @Override
    public void updateResources() {
        updateTile();
        super.updateResources();
    }

}

...但我不确定如何使用反射来做到这一点.这是我正在尝试扩展的类. 我也不确定如何覆盖方法并使用构造函数初始化对象.我使用反射处理过非常简单的事情,但从未处理过动态扩展另一个类.

...but I'm not sure how to do this using reflection. This is the class that I'm trying to extend. I'm also not sure as to how I would override a method and initialise the object using the constructor. I've worked with very simple things using reflection but never dealt with extending another class dynamically.

如果有人能用一些片段为我指明正确的方向,我相信我能从那里处理它.

If someone could point me in the right direction with some snippets, I'm confident that I'll be able to handle it from there.

推荐答案

你不能用反射来做到这一点.您可以使用 java.lang.reflect.Proxy 动态创建 interface 实现,仅此而已.

You can’t do that with reflection. You can create interface implementations dynamically using java.lang.reflect.Proxy but that’s it.

如果您想要更多,则必须使用第三方库.但是这些库通常在较低级别上工作,例如字节码,需要一些经验.并且它们不能在受限环境中使用.

If you want more you have to use third-party libraries. But these libraries usually work on a lower level, e.g. byte code and require some experience. And they cannot be used in restricted environments.

这篇关于如何使用反射动态创建一个扩展另一个动态类的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆