Boyang
Boyang

Reputation: 2576

Put my class into other people's package to access package visible methods?

I undeerstand it's certainly not a good practice, but does Java provide any mechanism to prevent accessing package-private methods/attributes? If not, does that mean this:

package com.other_people_other_company;

public class MyClass {
  // Let's hack! Access all package privates
}

is valid?

Edit:

It's mentioned in the answer:

Name: myCompany/myPackage/
Sealed: true

This is new info to me. But what if I sabotage by distributing a jar of mine, and sealing other people's package there? E.g. Name: org.apache Sealed: true

Upvotes: 2

Views: 123

Answers (2)

Esko
Esko

Reputation: 29375

Assuming .JAR distribution, you can seal the packages by adding the following lines to META-INF/MANIFEST.MF:

Name: myCompany/myPackage/
Sealed: true

A few notes:

  • Each package requires its own entry.
  • This doesn't prevent a crafty person from stripping out the lines from the manifest file and redistributing it internally. If this is a problem, you may need to look into some self validation techniques, such as enforcing the classes in sealed packages to check that the manifest has been left untouched.

Upvotes: 2

Andremoniy
Andremoniy

Reputation: 34920

Yes, that's true. On this idea some kind of "patch" method is based: when you have to fix some bug in 3d-party library you can create same package with same class in your classpath and create fixed class.

The only one restriction is special package names like java.util, e.g. this example will be successfully compiled, though java.util.Tripwire class has package local access modifier:

package java.util;

public class TestTripwire {
    public static void main(String[] args) {
        Tripwire.trip(Object.class, "sss");
    }
}

But if you run it you will get exception Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.util

Upvotes: 0

Related Questions