Best practice: Extending or overriding an Android library project class

前端 未结 7 1739
春和景丽
春和景丽 2020-12-04 15:31

We\'re using an Android Library Project to share core classes and resources across different builds (targets) of our Android application. The Android projects for each speci

7条回答
  •  星月不相逢
    2020-12-04 16:15

    Solution based on PoisoneR's solution and Turbo's solution.

    public static Class getExtendedClass(Context context, String clsName) {
    
        // Check for extended activity
        String pkgName = context.getPackageName();
        Logger.log("pkgName", pkgName);
        String extClassName = pkgName + "." + clsName + "Extended";
        Logger.log("extClassName", extClassName);
    
        try {
            Class extClass = Class.forName(extClassName);
            return extClass;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            // Extended class is not found return base
            return null;
        }
    }
    

    The benefits of this is that

    1. The extended class can be in the project's package, not the library's package. Thanks to Turbo for this part.

    2. By taking a String as an argument instead of a Class object, this method is able to be used even with ProGuard. getName() is where the problem is with ProGuard, as that will return something like "a" instead of the name of the original class. So in the original solution instead of looking for ClassExtended it will look for aExtended instead, something which does not exist.

提交回复
热议问题