我正在用JSF构建一个Java应用程序,它向API发出请求,获取JSON,并用JSON信息填充表……
代码如下:
@ManagedBean(name = "logic", eager = true)
@SessionScoped
public class Logic {
static JSONObject jsonObject = null;
static JSONObject jo = null;
static JSONArray cat = null;
public void connect() {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL("xxx");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while((inputLine = in.readLine())!= null){
System.out.println(inputLine);
sb.append(inputLine+"\n");
in.close();
}
}catch(Exception e) {System.out.println(e);}
try {
JSONParser parser = new JSONParser();
jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
jo = (JSONObject) cat.get(0);
jo.get("cif");
System.out.println(jo.get("cif"));
}catch(Exception e){System.out.println(e);}
}
private String cif;
final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
public ArrayList<Logic> getLogics() {
return logics;
}
public Logic() {
}
public Logic(String cif) throws ParseException {
this.cif = cif;
connect();
}
public String getCif() {
return cif;
}
public void setCif(String cif) {
this.cif = cif;
}
}在第67行-> final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
它在Netbeans中给出了这样的错误:未报告的异常ParseException;必须被捕获或声明为抛出。我尝试将它包含在try catch中,但它在code...what的其他部分给出了其他错误。我可以这样做吗,这样我就可以运行应用程序?
提前感谢
发布于 2020-01-28 21:09:39
据我所知,你尝试过
try {
final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
e.printStackTrace();
}问题是,这行代码不在方法中,并且您不能在其中使用try...catch。
解决此问题的一种快速方法是将该初始化放在static块中
public class Logic {
final static private ArrayList<Logic> logics;
static {
try {
logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
e.printStackTrace();
}
}
// rest of your class...
}但老实说,我想知道你为什么把logics声明为static。这在您的其余代码中并不明显。另外,我还看到你有一个非静态的getLogics()方法。所以我想说,如果真的没有理由把它声明为static,那就让它成为非静态的,并在构造函数中初始化它,在构造函数中,您可以尽情地使用try...catch。
https://stackoverflow.com/questions/59948201
复制相似问题