首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在cglib代理上实现接口有什么不同?

在cglib代理上实现接口有什么不同?
EN

Stack Overflow用户
提问于 2019-05-19 16:35:01
回答 1查看 142关注 0票数 1

我在Spring中使用ProxyFactory创建了2个代理对象。一个代理对象使用的接口和一个代理对象未使用的接口。但不能使用jdk动态代理。所有代理对象都使用cglib。实现接口代理对象调用real方法。未实现接口的代理对象具有意外结果。两个cglib代理对象有什么区别?两者之间唯一的区别是界面。

代码语言:javascript
复制
// Not implement interface
open class Person: AbstractPerson() {
}

abstract class AbstractPerson(var age: Int? = null,
                              var name: String? = null) {
    fun init() {
        this.age = 31
        this.name = "LichKing"
    }

    fun introduce(): String = "age: $age name: $name"
}
代码语言:javascript
复制
// Implement interface
open class PersonImpl: AbstractPersonImpl() {
}

abstract class AbstractPersonImpl(var age: Int? = null,
                                  var name: String? = null): PersonInterface {
    fun init() {
        this.age = 31
        this.name = "LichKing"
    }

    override fun introduce(): String = "age: $age name: $name"
}

interface PersonInterface {
    fun introduce(): String
}
代码语言:javascript
复制
// Test
class PersonTest {
    @Test
    fun implementInterface() {
        val p = PersonImpl()
        p.init()

        val proxyFactory: ProxyFactory = ProxyFactory()

        proxyFactory.setTarget(p)

        val proxy = proxyFactory.proxy as PersonImpl

        println(proxy.javaClass)
        println(proxy.introduce()) // "age: 31 name: LichKing"
    }

    @Test
    fun notImplementInterface() {
        val p = Person()
        p.init()

        val proxyFactory: ProxyFactory = ProxyFactory()

        proxyFactory.setTarget(p)

        val proxy = proxyFactory.proxy as Person

        println(proxy.javaClass)
        println(proxy.introduce()) // "age: null name: null"
    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-05-19 20:19:01

kotlin方法的默认选项是final。原因是introduce方法未被扩展。在使用接口时,默认选项是open,因此它可以扩展。

gradle plugin kotlin-spring只用于spring注解。它不适用于抽象类。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56206082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档