이 소스 코드에 어떤 문제가 있습니까?개체가 생성되었지만 여전히 null
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 }
I 선 (17) (실행 흐름의 순서로 언급) (18) (11), 오브젝트가 확실히 구성되고 중단 점을 설정 한, 또 라인 (18)에 객체 대신 null
를 리턴한다.
무엇이 누락 되었습니까?
정적 방법이 얼마나 나쁜지 알려주지 마십시오. 알고 있습니다. 왜 이런 일이 일어나고 어떻게 해결할 수 있는지 이해하도록 도와주세요.
저는 Linux x64에서 netbeans + glassfish + java 7 (openjdk)을 사용하고 있습니다.
부록
확인 문제가 내가 전화 했어 방법으로 할 수 있도록 - 나는 반사와 제네릭을 사용하고 있습니다.
호출자는 라인 (41) 내가 위의 방법 getNew()
를 호출하고있어에서이
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 }
것 같습니다. 키와 값 모두에 대해 null
초로 끝납니다.
라인 (28)에있어서,이 모든 혼란에 대한
return this.<Course>resultsetMap(Course.class, res);
죄송 같이이라고, 나는 원인 (평소와 같이, 바보)를를 찾은 다음 Course
클래스의 title
입니다 설정을 해제했다.
예외가 발생하지 않습니까? catch 절에 null을 반환하기 전에 printStackTrace 또는 이와 유사한 것을 추가하십시오. – z5h
당신은 당신이 삼키는 것으로 보이는'SQLException'을 실행하고 있지 않습니까? catch 블록에서 null을 반환하고 아마도 그것을 디버깅 할 수 있습니다. –
어쩌면 디버깅 할 항목과 정확히 null 값을 볼 수있는 부분을 지정해야합니다. 실행시 – Viruzzo