是否可以在Java中在运行时实现接口?

use*_*349 17 java bytecode

我正在开发一个项目,其中有很多由库创建的对象,我无法访问这些对象的创建过程.

以下片段是说明我的问题的一个很好的例子.

码:

public class Clazz {
    //The contents of Clazz are irrelevant
    //Clazz is NOT my class. I have no access to its internal structure.
    //However, I do have access to Clazz objects that were created elsewhere.
}
Run Code Online (Sandbox Code Playgroud)

ExampleInterface 是Clazz在编译时可能会或可能不会实现的接口.

码:

public interface ExampleInterface {
    public void run();
}
Run Code Online (Sandbox Code Playgroud)

以下代码是我遇到的问题.请注意以下事项:

  1. run()仅当c是其实例时才被调用ExampleInterface.
  2. getRunConditions(Clazz c)并且executeClazz(Clazz c)是我无法访问的类中的私有方法.
  3. 在编译时,Clazz包含名为方法run().
  4. ExampleExecutor 不是我的班级.我无法以任何方式访问它(我甚至无法获得该类的实例).

码:

public class ExampleExecutor {
    public void executeClazz(Clazz c) {
        if ((c instanceof ExampleInterface) && getRunConditions(c)) {
            ExampleInterface ex = (ExampleInterface) c;
            ex.run();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,以下方法在语法上是不可能的,但这正是我想要实现的.基本上,如果c尚未实现ExampleInterface,请将c设置为实现ExampleInterface,然后提供必须重写的方法.

请注意以下事项:

  1. extendInterface(Name of Interface)虚构的语法我在试图说明我的目标创建.
  2. run() 必须在这里定义(在运行时).
  3. 我不能使用包装器或代理类作为解决方案.IE,Clazz对象必须结束实现ExampleInterface,我不能使用解决方法.(如果你想知道原因,请参阅此链接).

码:

public void implementInterface(Clazz c) {
    if (!(c instanceof ExampleInterface)) {
        c.extendInterface(ExampleInterface {
            @Override
            public void run() {
                //code
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

为了澄清,我遇到的问题是我需要始终知道什么时候run()被调用Clazz.如果Clazz没有实现ExampleInterface,我不知道什么时候run()应该被调用.

同时,我还想偶尔添加支持run()默认情况下不支持的时间.因为我无法访问Clazz对象的创建,所以我不能通过自己实现接口来实现这一点.

问题:简单地说,是否可以在运行时实现接口(并提供所需的方法)?

注意:虽然唯一的解决方案可能需要反射(如果是这样,请在下面发布),我使用的库有一个安全管理器阻止所有反射的使用.IE,反射解决方案将来可能对其他人有用,但对我没用.

另外,我并不是说在我自己的程序中只使用库.已经运行的主机应用程序(我正在使用的库是这样做的)符合,然后运行我为它编写的代码.如果该应用程序不喜欢我提供的任何代码(IE,与其安全管理器冲突),则代码永远不会被编译.

为什么我需要这样做:

它与我正在使用的库有关.因为ExampleExecutor是一个我无法访问的方法,而且我无法控制Clazz的创建,我无法确定何时run()执行.

我需要知道何时run()执行的原因是因为实际上,它run()是一个事件处理程序,它是我正在使用的库的一部分.

例如:mouseClicked(CustomMouseEvent evt)可能是接口的一部分方法CustomMouseListener.有时,Clazz当我点击鼠标(因此继承CustomMouseListener)时,我正在小心地处理这个实例,而有时却没有.

Clazz实例不同,我总是关心单击鼠标,并始终需要触发事件.

实际上,ExampleInterface实际上将是以下内容:

public interface CustomMouseListener {
    public void mouseClicked(CustomMouseEvent evt);
    public void mousePressed(CustomMouseEvent evt);
    public void mouseReleased(CustomMouseEvent evt);
    //etc
}
Run Code Online (Sandbox Code Playgroud)

sab*_*ger 6

您可以使用java instrumentation API(强制)使类适应接口.APM,AOP框架和分析器通常使用此技术在运行时将日志记录和度量测量代码注入目标类.应用程序直接使用此技术是非常不寻常的.如果我在生产代码中看到这一点,那将至少是一个大红旗.

尽管如此,

鉴于这些Clazz:

package com.sabertiger.example;

public class Clazz {
    public void purr(){
        System.out.println("Hello world");
    }

}
Run Code Online (Sandbox Code Playgroud)

接口

package com.sabertiger.example;

public interface ExampleInterface {
    void run();
}
Run Code Online (Sandbox Code Playgroud)

执行者

package com.sabertiger.example;

public class ExampleExecutor {  
    public static void main(String[] args) {
        Clazz c=new Clazz();
        // Normally a ClassCastException
        ExampleInterface i=(ExampleInterface)(Object)(Clazz) c;
        i.run();
    }
}
Run Code Online (Sandbox Code Playgroud)

正常运行会产生此错误:

Exception in thread "main" java.lang.ClassCastException:
  com.sabertiger.example.Clazz cannot be cast to 
  com.sabertiger.example.ExampleInterface
    at com.sabertiger.example.ExampleExecutor.main(ExampleExecutor.java:7)
Run Code Online (Sandbox Code Playgroud)

您可以通过转换类来提供缺少的接口和实现,从而使其工作:

package com.sabertiger.instrumentation;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

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

public class ExampleInterfaceAdapter implements ClassFileTransformer {

    public static void premain(String agentArgument, Instrumentation instrumentation) {
        // Add self to list of runtime transformations
        instrumentation.addTransformer(new ExampleInterfaceAdapter());
    }

    @Override
    // Modify only com.sabertiger.example.Clazz, return all other unmodified
    public byte[] transform(ClassLoader loader, String className,
            Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
            byte[] classfileBuffer) throws IllegalClassFormatException {

        if(className.matches("com/sabertiger/example/Clazz")) {
            return addExampleInterface(className, classfileBuffer );            
        } else {
            return classfileBuffer;
        }
    }

    // Uses javassist framework to add interface and new methods to target class
    protected byte[] addExampleInterface(String className, byte[] classBytecode) {
        CtClass clazz= null;
        try {
            ClassPool pool = ClassPool.getDefault();
            clazz = pool.makeClass(new java.io.ByteArrayInputStream(classBytecode));

            String src=
              "{         "+
              "  purr(); "+
              "}         ";

            //Add interface
            CtClass anInterface = pool.getCtClass("com.sabertiger.example.ExampleInterface");
            clazz.addInterface(anInterface);

            //Add implementation for run method
            CtMethod implementation = CtNewMethod.make(
                    CtClass.voidType,
                    "run",
                    new CtClass[0],
                    new CtClass[0],
                    src,
                    clazz);
            clazz.addMethod(implementation);

            classBytecode=clazz.toBytecode();
        } catch(Throwable e) {
            throw new Error("Failed to instrument class " + className, e);
        }
        return classBytecode;
    }

}
Run Code Online (Sandbox Code Playgroud)

和所需的MANIFEST.MF

Manifest-Version: 1.0
Premain-Class: com.sabertiger.instrumentation.ExampleInterfaceAdapter
Boot-Class-Path: javassist.jar
Run Code Online (Sandbox Code Playgroud)

将所有东西装入罐子中以使其工作:

jar -tf agent.jar
META-INF/MANIFEST.MF
com/sabertiger/instrumentation/ExampleInterfaceAdapter.class
Run Code Online (Sandbox Code Playgroud)

现在我们可以将Clazz传递给ExampleExecutor

java -javaagent:agent.jar -classpath ..\instrumentation\bin com.sabertiger.example.ExampleExecutor
Hello world
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 5

提出建议的唯一方法是使用字节码Instrumentation。您可以添加一个代理,该代理会在加载之前更改要修改的clazz的字节码。

您需要在加载时执行此操作的原因是,许多JVM不允许您更改字段,而某些JVM不允许您在类加载后添加方法。

一个更简单的解决方案是反编译该类,对其进行修改然后再次对其进行编译。假设可以反编译该类,这将节省您大量的时间和精力。

我正在使用的库中有一个安全管理器,它阻止所有反射的使用

这是一个奇怪的选择,因为您可以在调用库之前放置自己的SecurityManager,并且不能阻止您执行任何操作。