0
我想在AspectJ中實例化非公共類的對象。AspectJ - 使用反射來實現非公共類的實體對象
我有這個類:
package ca1.business;
public class Bill {
int id;
String idOperator;
String idClient;
Bill(int id, String idOperator, String idClient) { /* (...) */ }
public String toString() { /* (...) */ }
public boolean equals(Object o) { /* (...) */ }
public int getId() { /* (...) */ }
public String getOperator() { /* (...) */ }
public String getClient() { /* (...) */ }
}
在各方面類我希望能夠做到:
Bill b = new Bill(currInvoice, idOperator, idClient);
的問題是,我得到一個錯誤:
The constructor Bill(int, String, String) is not visible
所以我調查並試圖使用反射,就像它在this後的解釋。
try {
Constructor<Bill> cons = Bill.class.getDeclaredConstructor(null);
cons.setAccessible(true);
Bill invoice = cons.newInstance(null);
invoice.id = 1;
invoice.idOperator = "foo";
invoice.idClient = "bar";
// etc...
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
但我得到的行錯誤:
invoice.id = 1;
invoice.idOperator = "foo";
invoice.idClient = "bar";
的錯誤是:
The field Bill.X is not visible.
有誰知道是否有什麼解決辦法?
請提供一個[mcve],其中包含**您的aspectj來源。 – GhostCat
在類Bill中,你有一個包私有構造函數 - 它不能從另一個包中看到,因此將其公開並調用Bill b = new Bill(currInvoice,idOperator,idClient);沒有反思。 – DontPanic