Proguard,Android和抽象类实例化

gjt*_*ian 2 android abstract-class proguard

"抽象类实例化",你说."不可能!"

这是我的代码:

public static AbstractFoo getAbstractFoo(Context context) {
    try {
        Class<?> klass = Class
                .forName("com.bat.baz.FooBar");
        Constructor<?> constructor = klass.getDeclaredConstructor(
                String.class, String.class);
        constructor.setAccessible(true);

        AbstractFoo foo = (AbstractFoo) constructor.newInstance(
                "1", "2");
        return foo;
    } catch (ClassNotFoundException e) {
        // Ignore
    } catch (NoSuchMethodException e) {
        throw new InflateException(
                "No matching constructor");
    } catch (IllegalAccessException e) {
        throw new InflateException("Could not create foo", e);
    } catch (InvocationTargetException e) {
        throw new InflateException("Could not create foo", e);
    } catch (InstantiationException e) {
        throw new InflateException("Could not create foo", e);
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

com.bat.baz.FooBar是一个扩展AbstractFoo的私有类.没有Proguard,此代码在我的Android设备上运行.有了它,它在NoSuchMethodException try/catch上失败了.

我继续在我的Proguard配置文件中添加语句,如

-keep public abstract class  AbstractFoo
{public *;protected *; private *;} 
Run Code Online (Sandbox Code Playgroud)

但这并没有解决问题.如何让Proguard接受这是实例化AbstractFoo对象的有效方法?至少,如果它在没有Proguard的情况下工作,它应该可以使用它.

Eri*_*une 7

ProGuard正在从代码中删除构造函数,因为它似乎未使用.ProGuard无法检测到反射调用构造函数.所以,你必须明确地保持它:

-keepclassmembers class com.bat.baz.FooBar {
  <init>(java.lang.String, java.lang.String);
}
Run Code Online (Sandbox Code Playgroud)

请注意,在ProGuard的帮助论坛上,您可能会有更多机会遇到类似问题.