简体   繁体   English

在不扩展类的情况下向其他文件中的Java类添加方法

[英]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. 我想创建一个访问私有方法createAuth的新公共方法,但是在另一个文件中。 Is there a way to create this new method without writing it or accessing it via an extended class? 有没有一种方法可以创建这个新方法而无需编写它或通过扩展类访问它?

Thank you. 谢谢。

No. You can't access a private method from an other class. 不可以。您不能从其他类访问私有方法。 Because it's ... private. 因为它是...私人的。

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). 一种解决方法可能是使用反射,但是由于多种原因(脆弱性,性能问题,破坏封装等),因此不建议使用此方法。

There is no clean and recommended general way to do this in Java. 在Java中,没有干净且推荐的通用方法来执行此操作。 private is private. 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). 您可以反编译Man的类文件,设置要保护或公开的所有内容,然后重新编译(并将其重新打包到jar文件中)。 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. 您可以使用字节码操作库编写自定义ClassLoader ,以在运行时修改类的字节码。 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. 两种方法都不是您可以使用的/应该用于常规应用程序或常规框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM