隐藏构造函数的抽象类实例 [英] Instance of abstract class with hidden constructor

查看:156
本文介绍了隐藏构造函数的抽象类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用隐藏的构造函数创建一个抽象类的实例,该类如下所示:

I need to create an instance of an abstract class with hidden constructor, the class looks like the following:

public abstract class TestClass {
    /**
    * @hide
    */
    public TestClass() {
    }
}

创建具体类不起作用,因为构造函数不可见并且通过反射API调用构造函数也不起作用因为类是抽象的。

creating an concrete class does not work, because the constructor is not visible and calling the constructor via reflection API also doesn't work because the class is abstract.

我需要创建一个android.print.PrintDocumentAdapter.LayoutResultCallback实例

I need to create an instance of android.print.PrintDocumentAdapter.LayoutResultCallback

推荐答案

我遇到了完全相同的问题(甚至是同一个类),我有一个更好的解决方案,而不是像其他答案所建议的那样用framework.jar替换android.jar。

I ran into precisely the same problem (for precisely the same class even) and I have a better solution than replacing the android.jar with framework.jar as suggested in the other answer.

该解决方案使用 dexmaker库。 (您将需要dexmaker.1.4.jar和dexmaker-dx.1.4.jar)。这是一个在运行时为Dalvik VM(在android中使用的VM)生成字节码的库。

The solution uses the dexmaker library. (You will need dexmaker.1.4.jar and dexmaker-dx.1.4.jar). This is a library that generates bytecode at runtime for the Dalvik VM (the VM used in android).

此库有一个名为 ProxyBuilder 的类,它为抽象类生成代理 。代理是扩展抽象类的对象,并通过将它们分派到 java.lang.reflect.InvocationHandler 的实例来实现这些方法。指定。

This library has a class called ProxyBuilder that generates a proxy for an abstract class. The proxy is an object that extends the abstract class and implements the methods by dispatching them to an instance of java.lang.reflect.InvocationHandler that you specify.

ProxyBuilder 几乎与 java.lang.refect.Proxy ,但 java.lang.refect.Proxy 仅适用于接口,而dexmaker的 ProxyBuilder 适用于抽象课程,这是我们的问题所需要的。

ProxyBuilder is almost identical to java.lang.refect.Proxy, except that java.lang.refect.Proxy only works for interfaces, while dexmaker's ProxyBuilder works for abstract classes, which is what we need for our problem.

代码全是:

public static PrintDocumentAdapter.LayoutResultCallback getLayoutResultCallback(InvocationHandler invocationHandler,
                                                                                File dexCacheDir) throws  IOException{
    return ProxyBuilder.forClass(PrintDocumentAdapter.LayoutResultCallback.class)
            .dexCache(dexCacheDir)
            .handler(invocationHandler)
            .build();
}

回调逻辑在 invocationHandler中实现
cacheDir 是dexmaker可以存储某些文件的目录。

The callback logic is implemented in the invocationHandler that you provide. The cacheDir is some directory where dexmaker can store some files.

这篇关于隐藏构造函数的抽象类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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