Get a class of an object : Intanceof « Language Basics « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » Language Basics » Intanceof 




Get a class of an object
 
 
import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    Person p = new Person("A");
    Animal a = new Animal("B");
    Thing t = new Thing("C");
    String text = "hello";
    Integer number = 1000;

    List<Object> list = new ArrayList<Object>();
    list.add(p);
    list.add(a);
    list.add(t);
    list.add(text);
    list.add(number);

    for (int i = 0; i < list.size(); i++) {
      Object o = list.get(i);
      if (instanceof Person) {
        System.out.println("My name is " ((Persono).getName());
      else if (instanceof Animal) {
        System.out.println("I live in " ((Animalo).getHabitat());
      else if (instanceof Thing) {
        System.out.println("My color is " ((Thingo).getColor());
      else if (instanceof String) {
        System.out.println("My text is " + o.toString());
      else if (instanceof Integer) {
        System.out.println("My value is " ((Integero));
      }
    }
  }
}

class Person {
  private String name;

  public Person(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }
}

class Animal {
  private String habitat;

  public Animal(String habitat) {
    this.habitat = habitat;
  }

  public String getHabitat() {
    return habitat;
  }
}

class Thing {
  private String color;

  public Thing(String color) {
    this.color = color;
  }

  public String getColor() {
    return color;
  }
}

   
  














Related examples in the same category
1.Finding Out of what Class an Object is Instantiated
2.The difference between instanceof and classThe difference between instanceof and class
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.