仿制药的使用方法 [英] Generics method usage
问题描述
我在C#代码:
private static T GetPage<T>() where T : new()
{
var page = new T();
PageFactory.InitElements(Browser.Driver, page);
return page;
}
public static AboutPage About
{
get { return GetPage<AboutPage>(); }
}
我试图用Java来实现这一点,因为我真的很喜欢这个概念,但我不擅长与仿制药(尤其是用C#)。所以,这是我的代码:
I was trying to implement this in Java, as I really liked the concept, but I'm not good with generics (and especially with c#). So, that's my code:
private static <T> T getPage(Class<? extends T> cls) throws Exception{
T page = cls.newInstance();
PageFactory.initElements(driver, page);
return page;
}
public static LoginPage Login() {
return LoginPage.getPage();
}
这是不工作的。我觉得我失去了基本面,所以我真的很感激任何帮助或建议
It's not working at all. I feel like I'm missing fundamentals, so I'd really appreciate any help or advice.
推荐答案
试试这个:
private static <T> T getPage(Supplier<? extends T> supp) {
T page = supp.get();
PageFactory.initElements(driver, page);
return page;
}
public static LoginPage Login() {
return getPage(LoginPage::new); // Passing the default constructor
}
下面我转出的实例 T
从类
,从供应商实例
,因为它没有。抛出异常
Here I switch out the instantiation of T
from Class
, to instantiation from a Supplier
, since it does not throw exceptions.
如果您没有安装Java 8,你必须使用你的代码,调用,如:
If you don't have Java 8, you would have to use your code, and call like:
getPage(LoginPage.class);
但是,这也意味着不必处理的异常。
But that would also mean having to deal with the exceptions.
这篇关于仿制药的使用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!