Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to check for class at runtime

Status
Not open for further replies.

ankursaxena

Programmer
Sep 7, 2001
133
US
Hi, I have 2 objects coming in to the socket, I have to see what class is it, whether it is Vector or Alarms class..how do i do this? If I have read the object into Object obj variable.

Thanks
Ankur
 
import java.io.*;

public class RTTI {

public static void main(String args[]) {
printRTTI(new Integer(7));
printRTTI(new DataOutputStream(System.out));
}

public static void printRTTI(Object o) {

if (o == null) {
System.out.println("This object is null");
return;
}
Class c = o.getClass();
printHierarchy(c);
printInterfaces(c);
printClassLoader(c);

}

static void printHierarchy(Class c) {
System.out.println(c.getName());
while ((c = c.getSuperclass()) != null) {
System.out.println("extends " + c.getName());
}

}

static void printInterfaces(Class c) {
Class[] ci = c.getInterfaces();
if (ci.length > 0) {
if (c.isInterface()) {
for (int i = 0; i < ci.length; i++) {
System.out.println("extends" + ci.getName());
}
}
else {
System.out.println("implements ");
for (int i = 0; i < ci.length; i++) {
System.out.println(ci.getName() + ",");
}

}
}
}

static void printClassLoader(Class c) {
ClassLoader cl = c.getClassLoader();
if (cl != null) System.out.println("This object was loaded by " + cl);
}

}
 
Would it not be easier to just do :

Code:
Object incoming ...
if (incoming instanceof java.util.Vector) {

} else if (incoming instanceof Alarm) {

} else {

}

--------------------------------------------------
Free Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top