Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to know if a certain variable is inside of a class?

 
Corey Hollaway
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


How would I know that the "kitKatBar" variable existed inside of the Corey class?
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a) read the sourcecode
b) read the documentation

you could use
c) use reflection
d) guessing

But a class without sourcecode and without docs is useless.
Throw it away.
 
Corey Hollaway
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How would I use reflection to see if kitKatBar existed inside of the Corey class?

This is the reason why I want to know:
------------------------------

I'm going to have a lot of people in a program using polymorphism. BUT, only some of them are going to be Athletes! And in main I'm going to have this:

People[] myPeople = new People[2];
myPeople = new Corey();
myPeople = new Sally();
for(int i=0; i<myPeople.length; i++){
if(They have the kitKatBar variable)
System.out.println(myPeople[i].name + " is an Athlete!");
}

Docs & source code can't help with this one! I need reflection? Thank you for your time! And your reply Stefan Wagner Peace out!
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64967
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a completely horrible way to do it. How about a boolean property that declares whether they are athletes or not... or use the polymorphism you mentioned to create a subclass of People that is Athlete?
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or, to use it as is, you could check instanceof Athlete. If it is, it has the variable. Although, i second Bear's assesment of the idea as a whole.
 
Corey Hollaway
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Bear Bibeault and Joseph George. I third Bear's approach. But let's say I was crazy, and I wanted to make my coworkers hate me (but I that's because I'm using this technique in a bad way, but next time it will be really good!). I like what you said about instanceof!

And I got it! I was working with the instanceof VARIABLE, but all I needed to do was if People[i] instanceof Athlete! I thought I couldn't do that! Thank you! Here's all of the code for who needs it!

Athletes.java:
-----------------------------------------

[ July 21, 2004: Message edited by: Corey Hollaway ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic