• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to cast to Anonymous Inner Class

 
D Rog
Ranch Hand
Posts: 472
Linux Objective C Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

How can I name anonymous class in cast? I do a trick, like comment out

and then do compilation. Now I can find my anonymous class name and put it in cast. It works flawlessly. However I have feeling I do something wrong. hey help to a java beginner.
 
Henry Wong
author
Marshal
Pie
Posts: 21431
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I can find my anonymous class name and put it in cast. It works flawlessly. However I have feeling I do something wrong. hey help to a java beginner.


Not sure what you mean here. Are you saying that you were able to cast it to the anonymous class type?

Henry
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to use the name of a class in your code, then you don't want it to be anonymous, right? Doesn't make sense to create a class with no name, and then work hard at figuring out its name. Just create a named inner class. You know you can create a class right inside a method, yes?

 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you just need to create the anonymous class instance and call a method on it, and nothing else, then you could skip the part where you assign it to a variable. Just do this:
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your example, you don't even need to cast to call doSomething. That's the whole point of polymorphism.
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
If you want to use the name of a class in your code, then you don't want it to be anonymous, right?

Very much so. In fact, you can't expect the name to stay the same. While today it might be mypackage.MyClass$2, it can change into mypackage.MyClass$3 quite easily if you add another anonymous class to your main class.
 
D Rog
Ranch Hand
Posts: 472
Linux Objective C Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all for answering.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic