作者SongIceFire (冰与火之歌)
看板java
标题[问题] java 观念请益
时间Fri Feb 5 07:21:09 2021
主要是来自於这个问题以及 github
https://stackoverflow.com/questions/32209248/java-util-stream-with-resultset
https://github.com/claudemartin/streamed-sql
在 Example.java 中
...
strsql.stream("SELECT * FROM FOO WHERE NAME LIKE 'L%' ORDER BY NAME", Foo::o
f))
...
这个
Foo::of 是建构式参考
但在 StreamedSQL.java 中 strsql.stream() 这个方法签署传入的是介面
public <T> Stream<T> stream(final String query, final ResultSetMapper<T> map
per) throws SQLException {
return stream(this.getDefConn(), query, mapper);
}
只知道静态方法签署中参数与回传值相同所以可使用建构式参考
但不清楚为何传入的是 ResultSetMapper 介面
以及从何得知T的实际型态为 Foo
另外 Foo::of 可以改用 lambda 写吗
谢谢
----
Sent from
BePTT
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 223.136.97.104 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/java/M.1612480872.A.ECB.html
1F:→ ssccg: 不是得知T型态为Foo,是因为用了Foo::of所以T才确定是Foo02/05 09:30
2F:→ ssccg: 方法或建构式参考就是参数和回传值跟函式介面的方法一样就02/05 09:34
3F:→ ssccg: 能拿来当介面实作,Foo::of 是 (ResultSet) -> Foo02/05 09:37
4F:→ ssccg: ResultSetMapper<T>的map是 (ResultSet) -> T02/05 09:37
5F:→ ssccg: 所以Foo::of可以实作ResultSetMapper<Foo>02/05 09:38
6F:→ SongIceFire: 先谢谢,我先再翻一下书看看这部分02/06 04:24
不要用 lambda 写反而很清楚
谢谢
....
try (final var conn = initDB()) {
final var strsql = StreamedSQL.create(conn, true);
try (Stream<Foo> stream = strsql.stream("select ... ", new ResultSetMapper<Foo>(){
@Override
public Foo map(ResultSet rs) throws SQLException{
return Foo.of(rs);
}
})) {
stream.filter(....);
}
}
....
※ 编辑: SongIceFire (223.136.97.104 台湾), 02/06/2021 13:00:10