user717236
user717236

Reputation: 5039

Adding a method to Java class in different file without extending the class

package com.companyxyz.api.person;

public class Man {
    public var1;
    public var2;
    ...
    private static void createAuth() {
    ...
    }
    // public methods go here
    ...
}

I want to create a new public method that accesses the private method, createAuth, but in a different file. Is there a way to create this new method without writing it or accessing it via an extended class?

Thank you.

Upvotes: 1

Views: 1058

Answers (3)

A.H.
A.H.

Reputation: 66263

There is no clean and recommended general way to do this in Java. private is private.

But you did not state why you want to do this and what the specific constraints are. Therefore I throw two options into the mix:

  • You can decompile the class file for Man, set everything you want to protected or public and recompile (and repackage into a jar file). Perhaps there is no need to decompile, perhaps some bit manipulation on the class file can do the job, too.

  • You can write a custom ClassLoader with a bytecode manipulation library to modify the bytecode of the class at runtime. Then you can also add additional access paths to the stuff you want. Note however that this is extremely advanced/complicated stuff.

Both ways are nothing you can use / should use for normal applications or the usual framework.

Upvotes: 1

Duncan Jones
Duncan Jones

Reputation: 69349

A private method is not accessible to any external classes, (this includes subclasses).

A workaround might be to use reflection, however this isn't a generally recommended approach for a number of reasons (brittleness, performance problems, breaking encapsulation, etc).

Upvotes: 4

Thierry
Thierry

Reputation: 5233

No. You can't access a private method from an other class. Because it's ... private.

Upvotes: 5

Related Questions