![](/img/trans.png)
[英]Verifying the calling of a non-static method of a private static nested class of a static outer class
[英]calling method from private static nested class
我有一個不太好的舊代碼,涉及使用私有靜態類的方法,我想知道是否可以調用此類中的方法。 我正在為此編寫測試。 我知道,如果這是一種方法,則可以通過反射來完成,但事實並非如此。
public class FiscalReport implements Report
{
private void readProductValueClass()
{
Connection dbc = null;
Statement st = null;
ResultSet rs = null;
String q = null;
try
{
dbc = db.getConnection();
dbc.setAutoCommit(false);
st = dbc.createStatement();
routerClassMap = new HashMap();
q = "SELECT * FROM sales_report";
rs = st.executeQuery(q);
while(rs.next())
{
ProductValueClassrc = new ProductValueClass(); // <---this new class
// is where it gets called...
.....
}
private static class ProductValueClass
{
public String name;
public String emp;
public String sale;
public String option;
public String value;
public Query q;
public Query qr
public Query sql;
public String toString()
{
return
"[" +
name + ", " +
emp + ", " +
sale + ", " +
option + ", " +
values +
"]";
}
public Query query()
{
return q.add(q(notEqual(qr)? null: sql));
}
}
}
我相信您正在尋找創建私有內部類的實例嗎? 如果是這種情況,此鏈接已經為您提供了一個解決方案: 使用Java反射實例化私有內部類
您可以像這樣訪問ProductValueClass的方法:
try {
//creating parent object
Object parent=new FiscalReport();
//creating inner class object
Class<?> innerClass=Class.forName("FiscalReport$ProductValueClass");
//inner object must know type of outer class
Constructor<?> constructor=innerClass.getDeclaredConstructor(FiscalReport.class);
//private inner class has private default constructor
constructor.setAccessible(true);
//inner object must know about its outer object
Object child = constructor.newInstance(parent);
//invoking method on inner class object
Method method = innerClass.getDeclaredMethod("wantedMethod",new Class<?>[]{});
method.setAccessible(true);//in case of unaccessible method
method.invoke(child,new Object[]{});
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
由於您的內部類是靜態的,請嘗試以下操作:
Class<?> clazz = Class.forName("FiscalReport$ProductValueClass");
Object c = clazz.newInstance();
Class<?> productValueClass = c.getClass();
Method toStringMethod = productValueClass.getMethod("toString", new Class<?>[] {});
toStringMethod.setAccessible(true);
System.out.println(toStringMethod.invoke(c));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.