Is it possible to implement an interface at runtime in Java?

前端 未结 4 1413
梦谈多话
梦谈多话 2021-02-01 20:29

I am working on a project where there are a lot of objects that are created by a library, and I have no access to the creation process of these objects.

The following sn

4条回答
  •  耶瑟儿~
    2021-02-01 21:00

    Depending on your java version, you could use the lambda expression (with java 8).

    The code would be relatively simple:

    Clazz o = .... // Here you obtain your object through third party library
    ExampleInterface yourInterface = o::run;
    yourInterface.run();
    

    Note that this only works for interface with one method. Both signatures (interface and Clazz) must match.

提交回复
热议问题