Reputation: 1
I have this simple Java class and I am just trying to pass the Type but I get always a Nullpointer Exception cause null is obviously Null WHY?
public class Main {
public static void main(String[] args) {
Box<String> test = new Box<>();
test.print();
}
//And the Generic Class
public class Box<T> {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
public void print () {
System.out.println(this.t.getClass());
}
}
Using JDK 12
Upvotes: 0
Views: 1154
Reputation: 21
You only new a Object Box<String>
,however you didn't initialize the private T t;
try something like this
Box<String> test = new Box<>();
test.set("the first way");
test.print();
or
public class Main {
public static void main(String[] args) {
Box<String> test = new Box<>("the second way");
test.print();
}
public class Box<T> {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
public Box(T t) {this.t = t}
public void print () {
System.out.println(this.t.getClass());
}
}
Upvotes: 1
Reputation: 103254
Whilst all other answers explain why you get the NullPointerException
, it's clear you want to retrieve, one way or another, the String
bit of your Box<String>
expression.
You can't; this is called erasure. Generics in expressions and local variable declarations are figments of the compiler's imagination; they are compiler-checked comments. Like comments. they cease to exist at runtime.
Generics in signatures (so, method return types, parameter types, types of fields, and any generics mentioned anywhere in your class declaration line, so, the A, B, and C in class Foo<A> extends Parent<B> implements Something<C>
) are recoverable using some very tricky and weird API (and you really don't want to, I think).
If you must be able to access single simple types, I suggest passing in the actual class object: new Box<String>(String.class)
.
Upvotes: 1
Reputation: 111
You get NullPointerException because reference of t variable is null. You are trying to access the variable before initialize it. Firstly, call the setter method. Then try to get it.
NullPointerException: NullPointerException Thrown when an application attempts to use null in a case where an object is required.
Here is the solution
Box<String> test = new Box<>();
test.set("hi!");
test.print();
Upvotes: 2
Reputation: 466
You only initialize your Box<String>
object, but you didn't set the T t
instance variable to anything.
As T is an Object its default value will be null.
Try setting it first, then calling print.
Box<String> test = new Box<>();
test.set("test");
test.print();
Upvotes: 0