You can use getClass() to get the java.lang.Class object that represents the type of the object.
view plaincopy to clipboardprint?
public void myMethod(Object obj) {
Class cls = obj.getClass();
System.out.println("The type of the object is: " + cls.getName());
}
If you just want to know if an object is an instance of or extends a certain class, or implements a certain interface, you can use the instanceof keyword.
view plaincopy to clipboardprint?
public void myMethod(Object obj) {
if (obj instanceof String) {
System.out.println("It's a String");
}
else {
System.out.println("It's not a String");
}
}
Code Example
class A
{
void Afoo()
{
System.out.println("I am from Afoo ");
}
}
class B extends A
{
void Bfoo()
{
System.out.println("I am from Bfoo ");
}
}
public class TypeofExampleClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
B oB = new B();
Class cls = oB.getClass();
System.out.println("cls.getName() = " + cls.getName());
String x="hello";
cls = x.getClass();
System.out.println("cls.getName() = " + cls.getName());
if (x instanceof String) {
System.out.println("x is a String");
}
else {
System.out.println("x is not a String");
}
if (oB instanceof B) {
System.out.println("oB is a B");
}
else {
System.out.println("oB is not a B");
}
if (oB instanceof A) {
System.out.println("oB is a A");
}
else {
System.out.println("oB is not a A");
}
}
}
Thursday, October 6, 2011
Subscribe to:
Post Comments (Atom)
Blog Archive
-
▼
2011
(120)
-
▼
October
(29)
- Using Java to Handle Custom WSDL Data Types
- Parse WSDL effectively
- Create SOAP Request with Java
- Parsing WSDL with Java
- Understanding WSDL - Basics
- Java - Simple Iterator
- Java - Traversing a map
- Creating SOAP Message Handlers in 3 Simple Steps -...
- Adding a new library to NetBeans
- JQuery
- Planning to Build vs. Building the Plan
- Project Workplan
- 7 Tips for Improving the Daily Scrum
- Hide div and the white space it occupies
- Manually Deploy JAX-WS Web Service on Tomcat - Per...
- Web Service Client - Eclipse
- Axis2 RPC Support
- WSDL to JAVA and Axis2
- Web Service Style Types
- Web Services with Complex Data Type
- WSDL2Java Reference
- Java2WSDL Reference
- Axis2 Web Service and Client - Perfect Tutorial
- Determining if an Object is of primitive type
- Associative arrays
- axis2 - Simpe Hello World Service
- Java - getting type of Object
- WSDL - Complex Data Types
- Java - Hash Map Example
-
▼
October
(29)
No comments:
Post a Comment