在kotlin中扩展DataInputStream

时间:2018-01-22 12:54:58

标签: kotlin

我已经将DataInputStream子类化,并添加了little-endian方法。请注意,我添加了一个代表原始inp的新InputStream属性。我需要在新方法中引用此属性。以下代码工作正常:

import java.io.*
import org.apache.poi.util.*

class MyDataInputStream(val inp: InputStream) : DataInputStream(inp) {

    fun readShortLittle(): Short {
        val r: Short
        try {
            r = LittleEndian.readShort(inp)
        } catch (e: LittleEndian.BufferUnderrunException) {
            throw EOFException()
        }
        return r
    }

    fun readIntLittle(): Int {
        val r: Int
        try {
            r = LittleEndian.readInt(inp)
        } catch (e: LittleEndian.BufferUnderrunException) {
            throw EOFException()
        }
        return r
    }

    fun readLongLittle(): Long {
        val r: Long
        try {
            r = LittleEndian.readLong(inp)
        } catch (e: LittleEndian.BufferUnderrunException) {
            throw EOFException()
        }
        return r
    }
}

fun main(args: Array<String>) {
    var i: Int
    val inp = MyDataInputStream(System.`in`)
    while (true) {
        // llegir int en binari si EOF break
        try {
            i = inp.readIntLittle()
        } catch (e: EOFException) {
            break
        }
        println(i);
    }
}

但我想知道如何使用扩展方法执行此操作,例如:

fun DataInputStream.readShortLittle(): Short {
    ...
}

fun DataInputStream.readIntLittle(): Int {
    ....
}

fun DataInputStream.readLongLittle(): Long {
    ....
}

定义新的inp属性时出现问题。

1 个答案:

答案 0 :(得分:0)

严格来说,你不能,因为它可以通过扩展方法看不到的protected字段访问。但是使用this代替inp应该有效,因为LittleEndian.read方法会在read上调用DataInputStreamin.read将委托给@Entity @Table(name = "USERS") public class User extends Abstract { @Column(name = "FIRST_NAME", nullable = false, length = 100) private String firstName; @Column(name = "LAST_NAME", nullable = false, length = 100) private String lastName; @Column(name = "EMAIL", nullable = false, length = 100) private String email; @Column(name = "PASSWORD", nullable = false, length = 60) private String password; @Column(name = "PHONE_NUMBER", nullable = false, length = 20) private String phoneNumber; @Column(name = "BIRTHDATE", nullable = false, columnDefinition = "TIMESTAMP") private LocalDateTime birthdate; @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name = "USERS_CONTACTS", joinColumns = @JoinColumn(name = "USER_ID", foreignKey = @ForeignKey(name = "FK__USERS__USERS__USER_ID")), inverseJoinColumns = @JoinColumn(name = "CONTACT_ID", foreignKey = @ForeignKey(name = "FK__USERS__USERS__CONTACT_ID"))) private List<User> contacts; // getters and setters }