gpt4 book ai didi

java - 对象构造但仍然为空

转载 作者:行者123 更新时间:2023-11-29 07:17:00 25 4
gpt4 key购买 nike

这个源代码有什么问题?

 1  package Core;
2
3 import java.sql.*;
4
5 public class Course extends Model {
6
7 protected int id;
8 protected String title;
9
10 public Course(int id) {
11 this.id = id;
12 }
13
14 public static Course getNew(ResultSet res) {
15 try {
16 Course c;
17 c = new Course(res.getInt("course_id"));
18 return c;
19 } catch(SQLException e) {
20 return null;
21 }
22 }
23
24 @Override
25 public String toString() {
26 return this.title;
27 }
28 }

我在第 17、18 和 11 行设置了断点(在执行流程的顺序中提到),对象肯定是构造的,但是在第 18 行它会返回一个 null 而不是对象。

我错过了什么?

请不要告诉我静态方法有多糟糕,我知道。帮助我了解为什么会发生这种情况以及如何解决它。

我在 linux x64 上使用 netbeans + glassfish + java 7 (openjdk)。

附录

好吧,问题可能出在我的调用方式上——我正在使用反射和泛型。

调用者看起来像这样

 1  package Core;
2
3 import java.sql.*;
4 import java.util.*;
5 import java.lang.reflect.*;
6
7 /**
8 * Represents storable elements in a database
9 */
10 public abstract class Model {
11 /**
12 * this attribute is common to all models of the app
13 * this way we can reuse the same connection for
14 * everything (good or bad, depending on the project's requirements; in
15 * our case it's good - this should be a simple application, no mysql
16 * replication and things like that)
17 */
18 protected static Connection conn = null;
19
20 public static void setConnection(Connection c) {
21 Model.conn = c;
22 }
23
24 public static void initStatements() throws SQLException {
25
26 }
27
28 protected <T extends Model> HashMap<String, Model> resultsetMap(Class<T> cls, ResultSet res) {
29 HashMap<String, Model> data = new HashMap<String, Model>();
30 Method m;
31 try {
32 m = cls.getMethod("getNew", ResultSet.class);
33
34 } catch(Exception e) {
35 return null;
36 }
37
38
39 try {
40 while(res.next()) {
41 T obj = (T) m.invoke(null, res);
42 data.put(obj.toString(), obj);
43 }
44 }
45 catch(Exception e) {
46 return null;
47 }
48 return data;
49 }
50
51 @Override
52 public abstract String toString();
53
54 public static Model getNew(ResultSet res) {
55 return null;
56 }
57 }

在第 41 行,我调用了上述方法 getNew()。我最终在映射中得到了 null,包括键和值。

第28行的方法是这样调用的

return this.<Course>resultsetMap(Course.class, res);

抱歉所有的困惑,我找到了(像往常一样愚蠢)原因:title Course 类未设置。

最佳答案

如果到达第 18 行,则它不能为 null。但是,如果您调试的是旧版本,或者您只是没有到达第 18 行,则可能是您进入了异常的 catch block 。

因此,经验法则 - 不要丢弃异常。首先,使用 ex.printStackTrace() 在控制台中查看它。

然后直接试试return new Course(res.getInt("course_id"));

关于java - 对象构造但仍然为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8729364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com