So I'm just started to learn Java in school for like a month now, and I have this homework to make a simple Twitter-based social network. But I haven't learned database yet so we just making a simple database in the program.
Now the part where I get the error is that I instead of using switch, I used Reflection to call the methods in another class. And I get the NullPointerException error. I have read What is a NullPointerException, and how do I fix it? but I don't know how to fix it.
JavatterController.java
package jp.ac.kcg.java1;
public class JavatterController {
Javuser currentUser;
Database db;
public JavatterController(int index) {
db = new Database();
currentUser = db.getUser(index);
System.out.println(currentUser.getUserIdWithAt() + " has logged in!");
}
public void tw(String tweet) {
Tweet newTweet = new Tweet(tweet, currentUser.userId);
db.insertTweet(newTweet);
System.out.println(currentUser.getUserIdWithAt() + " just tweeted " + tweet);
}
Javatter.java
try {
// load the AppTest at runtime
Class<?> cls = Class.forName("jp.ac.kcg.java1.JavatterController");
Object obj = cls.newInstance();
// call the printItString method
Method method = cls.getDeclaredMethod(input[0], paramString);
method.invoke(obj, new String(input[1]));
} catch(Exception ex) {
ex.printStackTrace();
}
And this is the error I got
@manofsteel > tw lol
@manofsteel > java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at jp.ac.kcg.java1.Javatter.main(Javatter.java:48)
Caused by: java.lang.NullPointerException
at jp.ac.kcg.java1.JavatterController.tw(JavatterController.java:39)
... 5 more
So where did I do wrong and how can I fix it? Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire