Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Load class using string

 
Michelle de Beer
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To begin with, I am pretty new to Java, so I might have the logic all wrong, but please bear with me...

In short, I want to be able to load a class using a string (the name of the class) and trigger a method in it.

This is an illustative explanaition of my problem.

I have three classes.

1. RightMenu.java
2. LeftMenu.java
Both these have a method called clicked() that prints "Left" or "Right" to System.out.println();

In the third class, a Canvas class, I have a keyPressed()-method that catches user input.
If the left soft button is pressed I want to trigger RightMenu.clicked() and the same for the right soft button.

I thought this could do the trick, but it didn't.


When building, I get this error message:
d:\JAVA\WTK22\apps\PLATHINIUM2\src\Day.java:209: cannot resolve symbol
symbol : method clicked ()
location: class java.lang.Object
tmpCl.clicked();

// Any thoughts?
Michelle
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll want to take a closer look at Reflection in order to do what you want. Specifically Invoking Methods.
[ June 01, 2005: Message edited by: Gregg Bolinger ]
 
arnel nicolas
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i guess you need to cast your TmpCl object to LeftMenu class before calling the clicked() method.


On the second thought, i think you also need to put the LeftMenu class into a package like

to make sure that it is really loading.
[ June 01, 2005: Message edited by: arnel nicolas ]
 
Michelle de Beer
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This makes sense... But what if I didn't know the name of the Class, how would I cast it to make it work?

New explanatory code:
 
arnel nicolas
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Michelle de Beer:
This makes sense... But what if I didn't know the name of the Class, how would I cast it to make it work?

Hmmmmm....I don't get it, i assume that LeftMenu is an implementation of an interface, something like ILeftMenu, to make sure that your objects are in the same class hierarchy to avoid ClassCastException. Using string to cast an object does not make any sense either unless you want your code to end up to this site..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic