Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prune a Java program

Let's me start from what I want to do then raising some questions I have.

I want to develop a general Java program which is a superset of a number of programs (let's call them program variants). In particular, the general program has methods which are only used by one or more program variants (but not all). Given a particular configuration, I want to remove unnecessary methods and just keep the smallest set of methods for one program variant.

For example, I have a general program as below:

public class GeneralProgram {

    // this method is common for all variants
    public void method1() {};

    // this method is specific to variant 1
    public void method2() {};

    // this method is specific to variant 2
    public void method3() {};
}

Then after pruning the program based on configuration for variant 1, the result is

public class GeneralProgram {

    // this method is common for all variants
    public void method1() {};

    // this method is specific to variant 1
    public void method2() {};
}

It doesn't matter if the resulting class name is the same as the original one or not. I just want to prune the content of the class.

So, here are my questions:

  1. Do you have any idea how to realize this except low level text processing?

  2. I know that I can use aspectJ to disable/enable specific methods at runtime but what I really want to do is performing this task before deploying the program. Is there any technique in Java for this purpose?

like image 876
tuan Avatar asked Jun 18 '11 03:06

tuan


1 Answers

It seems to me that the right solution here is to use some object oriented programming and layer your program:

base.jar contains:

package foo.base;
class GeneralProgram {
   public void method1(){ }
}

var1.jar contains:

package foo.var1;
import foo.base.GeneralProgram;
class GeneralProgramVar1 extends GeneralProgram {
   public void method2(){ }
}

var2.jar contains:

package foo.var2;
import foo.base.GeneralProgram;
class GeneralProgramVar2 extends GeneralProgram {
   public void method3(){ }
}

Some deployments will have both base.jar and var1.jar, others will have base.jar and var2.jar. You'll have to mess with the classpaths a bit to resolve the dependencies.


If you can separate your variants well enough so that there are truly unused functions then you can use a compression utility like ProGuard to remove unused methods from the classes. You might find, however, that the effort required to reap the benefits of ProGuard are the same as the structure I recommend above.

like image 77
Mark Elliot Avatar answered Oct 12 '22 18:10

Mark Elliot