I have a not so good legacy code involving in using the method of a private static class I was wondering if the method in such class can be called. Which I was writing test for. I know it can be done with reflection if this was a method but it isnt.
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));
}
}
}
I believe you are looking to create an instance of the private inner class? IF that is the case, this link already has a solution for you: Instantiate private inner class with java reflection
You can access the methods of ProductValueClass like this:
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();
}
Since your inner class is static try this:
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.