Click to See Complete Forum and Search --> : Java question
Josh42
11-15-2001, 11:05 PM
Hi everybody. I have a java question here. . .
v is a Vector.
the Vector holds Objects that contain a getName() method.
Why does the following line give me a "cannot resolve symbol" error??? How do call a method stored in a Vector? Thank you!
v.elementAt(3).getName();
qball
11-16-2001, 03:42 PM
v.elementAt(3).getName();
try:
v.elementAt(3).getClass().getName();
bobcat
11-16-2001, 08:25 PM
You need to explicitly cast the Object in the vector. So, if you stored an Object instantiated from class Person, you would cast it w Person.
((Person)v.elementAt(2)).getName();
qball
11-18-2001, 07:25 PM
bobcat,
You need to explicitly cast...
How does one accomplish this, if they don't know what object is contained in the vector element? Else, what need getName()?
v.elementAt(index).getName();
Fails, as no getName method exists for an Object object.
http://java.sun.com/products/jdk/1.1/docs/api/java.lang.Object.html
getName() exists for the Class object.
http://java.sun.com/products/jdk/1.1/docs/api/java.lang.Class.html
Thus:
v.elementAt(index).getClass().getName();
This is kinda sorta called: Reflection.
bobcat
11-19-2001, 04:52 PM
If you know what Object is stored in the Vector you can explicitly cast it as I stated above. If you don't, and you need to do it on the fly; its reflection as qball has stated.
Here is a template of code that you can use.
Lets say you have many different Objects that have the getAddress() method returning a String of an address.
import java.lang.reflect.Method;
.
.
.
Class c = v.elementAt(index).getClass();
try {
Method m = c.getMethod("getAddress", new Class[] { } );
String s = (String)m.invoke(v.elementAt(index),new Object[] { });
// Do something w s.
}
catch (Exception e) {
}
SysOpt.com
Copyright Internet.com Inc. All Rights Reserved.