我有一个不太好的遗留代码涉及使用私有静态类的方法我想知道是否可以调用此类中的方法。我正在写测试。 我知道如果这是一种方法,它可以通过反射完成,但它不是。
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));
}
}
}
答案 0 :(得分:0)
我相信您正在寻找创建私有内部类的实例?如果是这种情况,此链接已经为您提供了解决方案: Instantiate private inner class with java reflection
您可以像这样访问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));