0

If I want to flatten all my package hierarchy, how can I proceed and what are the gotchas?

Note that this question is not about why I want to do this, but how. Valid reasons, for example, would include (but would not be limited to) several of the reasons that make Proguard a useful program.

At first I'd like to keep the class names intact but remove all the hierarchy.

So:

  • com.acme.example.SomeClass should become either "SomeClass" or
    "a.SomeClass"
  • com.acme.sample.AnotherClass should become either
    "AnotherClass" or "a.AnotherClass"

I did a quick check and out of about a thousand classes there aren't two with duplicate names:

find . -iname "*java" | sed 's/.*\///g' | sort | wc -l

and:

find . -iname "*java" | sed 's/.*\///g' | sort | uniq | wc -l

both give the same number of .java files (so I'm pretty sure there aren't any "duplicate names" in the *.java files).

I was thinking about writing a shell script that would:

  • remove (or modify) the package line
  • remove every "import com.acme...." line

Would this work?

What could be the things preventing this from working? What would happen from a public/protected/default/private visibility point of view?

I guess reflection would break havoc here but thankfully we're not doing any.

Note that I only want to do that on my own classes: I don't want to modify external APIs / jars.

Cedric Martin
  • 5,945
  • 4
  • 34
  • 66

1 Answers1

2

You should have a look at proguard. It's a code obfuscator with a bunch of options including flattening packages and not obfuscating other things if you don't want to.

mac
  • 5,627
  • 1
  • 18
  • 21
  • I mentioned Proguard in my question, so I know it ; ) However I didn't know it was able to flatten the package hierarchy. That's because Proguard's terminology is apparently a bit weird: it calls "flattening" was is simply "shortening" and the real "flattening" into a single package is called "repackaging" : ) I didn't know about this option, I'm going to try it out! – Cedric Martin Oct 13 '12 at 17:56
  • Sorry, I read over your question too quickly. In proguard 4.8 (maybe earlier versions too) there is a `-flattenpackagehierarchy` option which seems to do what you want. – mac Oct 13 '12 at 18:00