• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing a static variable from a generic class?

 
Sidharth Panwar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MyGeneric<T>
{
static int i;
---- Other stuff ----
}

class TestGeneric
{
public static void main(String[] args)
{
System.out.println(MyGeneric<String>.i);
}
}

Gives a compile-time error:
illegal start of expression - System.out.println(MyGeneric<String>.i);
^

What is the problem?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Paul Clapham
Sheriff
Posts: 21111
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generics are a compile-time artifact. In your example there is only one "MyGeneric" class at run-time and only one instance of the static variable "i". Mentioning the class parameter when trying to access it is pointless and hence wrong.
 
Sidharth Panwar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Garrett Rowe:


Thanks Gerrett, didn't think about trying it this way.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic