我正在从事个人项目,发现如果应用 lambda,我可以复制更少的代码。
所以当前的代码看起来像这样:
public UserDto findByUsernameAndPassword(String username, char[] password) {
Properties props = new Properties();
props.put("java.naming.factory.url.pkgs","org.jboss.ejb.client.naming");
try {
InitialContext ctx = new InitialContext(props);
String ejbUrl = "ejb:ShopManagmentEAR/ShopManagmentEJB//FrontController!"+IFrontControllerRemote.class.getName();
IFrontControllerRemote bean = (IFrontControllerRemote) ctx.lookup(ejbUrl);
return bean.findByUsernameAndPassword(username, password);
} catch (NamingException e) {
System.out.println("error");
e.printStackTrace();
}
return null;
}
public List<CategoryDto> getAllCategories(){
Properties props = new Properties();
props.put("java.naming.factory.url.pkgs","org.jboss.ejb.client.naming");
try {
InitialContext ctx = new InitialContext(props);
String ejbUrl = "ejb:ShopManagmentEAR/ShopManagmentEJB//FrontController!"+IFrontControllerRemote.class.getName();
IFrontControllerRemote bean = (IFrontControllerRemote) ctx.lookup(ejbUrl);
return bean.getAllCategories();
} catch (NamingException e) {
System.out.println("error");
e.printStackTrace();
}
return null;
}
如您所见,这两种方法仅在返回的类型和 return 语句中的方法不同。所以我很确定lambda可以帮助我清除代码,但不幸的是我无法理解这个主题。
您可以创建泛型方法
private <T> queryBean(Function<IFrontControllerRemote,T> transform) {
Properties props = new Properties();
props.put("java.naming.factory.url.pkgs","org.jboss.ejb.client.naming");
try {
InitialContext ctx = new InitialContext(props);
String ejbUrl = "ejb:ShopManagmentEAR/ShopManagmentEJB//FrontController!"+IFrontControllerRemote.class.getName();
IFrontControllerRemote bean = (IFrontControllerRemote) ctx.lookup(ejbUrl);
return transform.apply(bean);
} catch (NamingException e) {
System.out.println("error");
e.printStackTrace();
}
return null;
}
随着呼叫
return queryBean(bean -> bean.findByUsernameAndPassword(username, password));
和
return queryBean(bean::getAllCategories);
分别。
为了利用lambda表达式(或方法引用(,您应该尝试弄清楚如何通过函数接口(即具有单个方法的接口(来表示两种方法之间的差异。
这两种方法都从IFrontControllerRemote
实例获取返回值。因此,泛型方法可以接受Function<IFrontControllerRemote,T>
,其中T
表示返回值。Function<IFrontControllerRemote,T>
实例将接受IFrontControllerRemote
并返回所需的值。
public <T> T getProperty(Function<IFrontControllerRemote,T> retriever) {
Properties props = new Properties();
props.put("java.naming.factory.url.pkgs","org.jboss.ejb.client.naming");
try {
InitialContext ctx = new InitialContext(props);
String ejbUrl = "ejb:ShopManagmentEAR/ShopManagmentEJB//FrontController!"+IFrontControllerRemote.class.getName();
IFrontControllerRemote bean = (IFrontControllerRemote) ctx.lookup(ejbUrl);
return retriever.apply(bean);
} catch (NamingException e) {
System.out.println("error");
e.printStackTrace();
}
return null;
}
现在,调用该方法:
UserDto user = getProperty (b -> b.findByUsernameAndPassword(username, password));
List<CategoryDto> list = getProperty (IFrontControllerRemote::getAllCategories);