我只是想尝试一下 java 8 。我有一个类,有一个名为 QuestionType 的字段。并且此类中的其他一些字段应根据 QuestionType 字段保存到其各自的表中。例如,如果问题类型是 MCQ,则其选项应保存在选项表中,类似地,如果问题类型是 PASSAGE,则其段落应保存在段落表中。
我创建了一个功能界面,如下所示:
@FunctionalInterface
public interface SaveQuestion {
void identifyAndSaveQuestion(Questions q,String type);
}
我的类(class)是:
public class QuestionDTO {
private Questions question;
private List<QuestionAnswer> answers;
private List<QuestionOptions> options;
String QuestionType type;
String passage;
//getter setter
}
我不确定,但我的功能应该类似于
void saveQuestion(Questions q,String type,SaveQuestion sq){
//cant figure out what to do here in java 8 style
}
如果您觉得我的问题很愚蠢,我真的很抱歉。我刚刚了解 java 8 的概念,说实话,我什至不知道是否可以用 java 8 风格来做。所以请考虑这是否是一个愚蠢的问题:)。任何帮助都会有很大帮助
最佳答案
Java 8 lambda 与其说是像函数一样使用接口(interface),不如说是快速实现它们。人们可能会实现您的函数,该函数仅使用 Java 8 中与以前版本相同的接口(interface):
void saveQuestion(Questions q,String type,SaveQuestion sq){
sq.identifyAndSaveQuestion(q,type);
}
但是,人们可以使用它来即时实现新的实现,其语法比使用匿名类更简洁。而不是这个:
saveQuestion(q, type, new SaveQuestion() {
@Override
public void identifyAndSaveQuestion(Questions q, String type) {
System.out.println("type ="+type+", questions="+q);
}
});
可以写:
saveQuestion(q, type, (qs,t) -> {
System.out.println("type =" + t + ", questions=" + qs);
});
对于数据库更新,您可能会提前在某处设置连接并准备好语句:
final java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?"
+ "user=somebody&password=mypwd");
final java.sql.PreparedStatement p = con
.prepareStatement("update mytable set questions=? where type=?");
...
然后使用它:
saveQuestion(q, type, (qs, t) -> {
try {
p.setString(1, qs.toString());
p.setString(2, t);
p.execute();
} catch (SQLException ex) {
// handle exception
}
});
注意,仍然需要捕获已检查的异常。
如果人们想要将 SaveQuestion 接口(interface)的许多不同实现传递给 saveQuestion 函数,他们的代码可以更紧凑,因为 SaveQuestion 是一个函数式接口(interface)。无论如何,saveQuestion 内的代码可能是相同的。
关于java - 使用java 8中的函数式接口(interface)根据数据类型将数据保存到不同的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31986036/