dongliu8559 2018-09-15 11:33
浏览 37
已采纳

如何在Java中编写等效于匿名类的内容?

This is more of a generic Go question related to interfaces/functions/closures/types/..., but with a concrete use case of performing I/O.

Given an io.Reader variable I want to create an io.ReadCloser with a custom Close() implementation.

var file os.File
file = ... // some File which needs to be closed

var reader io.Reader
reader = ... // get Reader from somewhere

var readCloser io.ReadCloser
readCloser = ... // how to create a ReadCloser here?

In Java, I would write something like:

readCloser = new io.ReadCloser() {
    Read(p []byte) {
        reader.Read(p);
    }

    Close() {
        // my custom close implementation
        file.Close()
    }    
}

// now pass readCloser around as needed

How to do that with Go?

  • 写回答

2条回答 默认 最新

  • drelgkxl93433 2018-09-20 03:00
    关注

    taking a hint from http.HandlerFunc , i could think of the following

    package main
    
    import (
        "bytes"
        "fmt"
        "io"
        "strings"
    )
    
    // ReadData reads data from an io.Reader
    func ReadData(r io.Reader) {
        buf := new(bytes.Buffer)
        buf.ReadFrom(r)
        s := buf.String()
        fmt.Printf("read : %s 
    ", s)
    }
    
    // ReaderFunc takes a function and returns io.Reader
    type ReaderFunc func([]byte) (int, error)
    
    func (r ReaderFunc) Read(b []byte) (int, error) {
        return r(b)
    }
    
    func main() {
        // invoking ReadData with a regular io.Reader
        r := strings.NewReader("data 123")
        ReadData(r)
    
        // invoking ReadData with an anonymous io.Reader
        r = strings.NewReader("data 456")
        ReadData(ReaderFunc(func(b []byte) (int, error) {
            return r.Read(b)
        }))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器