gpt4 book ai didi

java - 调用 super.super.method,跳过 super.method

转载 作者:搜寻专家 更新时间:2023-11-01 03:03:41 27 4
gpt4 key购买 nike

我有以下(第三方)类结构。我们将调用第三方项目 ProjectSeriously,并注意我使用 System.out.println 代替其他复杂的功能(100 行代码) .

class A {
public void hi() {
// Do an important thing
System.out.println("Important thing A");
}
}

class B extends A {
public void hi() {
// Do some terrible, terrible things
System.out.println("TERRIBLE THING B");

// Do that important thing
super.hi();
}
}

现在我想写这个(这不是有效的 java):

class C extends B { 
public void hi() {
// Do some not-so-terrible things
System.out.println("Ok thing C");

// Do that important thing
super.super.hi();
}
}

我必须将 instanceof B 传递给这个精彩项目 ProjectSeriously 的其他部分。鉴于这些是公共(public)方法,我觉得这应该是可能的。

最佳答案

你可以使用 javassist 使用它之前修改类。

但这是一个非常丑陋的 hack,请尝试重构 A 和/或 B 中的代码以暴露重要部分。

package test;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;

class A {
public void hi() {
// Do an important thing
System.out.println("Important thing A");
}
}

class B extends A {
public void hi() {
// Do some terrible, terrible things
System.out.println("TERRIBLE THING B");

// Do that important thing
super.hi();
}
}

class C extends B {
public void hi() {
// Do some not-so-terrible things
System.out.println("Ok thing C");

// Do that important thing
super.hi();
}
}

public class Main {

public static void main(String[] args) throws Exception {
CtClass cc = ClassPool.getDefault().get("test.B"); // don't use test.B.class.getName() as this force the class loader to load the class
CtMethod m1 = cc.getDeclaredMethod("hi");
cc.removeMethod(m1);
CtMethod m2 = CtNewMethod.copy(m1, cc, null);
m2.setBody("{ /* override method B.hi() body */ return super.hi();}", "this", m1.getName());
cc.addMethod(m2);
cc.toClass();
C obj = new C();
obj.hi();
}
}

结果:

Ok thing C
Important thing A

关于java - 调用 super.super.method,跳过 super.method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29928606/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com