stackoverflow
stackoverflow

Reputation: 19444

Java How would you use instanceof to return a new object types?

if you have the following

  1. Interface: Meal
  2. Hotdog implements Meal
  3. Burger implements Meal
  4. Salad implements Meal

How would you create a method to take in one of these object types to return the appropriate object?

Example:

Method makeFood(HotDog)

if(HotDog instanceof Meal)
 return new HotdogObject();

How do you correctly do this?

I'm working with

static public Food createMeal(Meal f)
      throws Exception
  {

    if (f instanceof Hotdog)
    {
      return f = new HotDog();
    }
    if (f instanceof Burger)
    {
      return f = new Burger();
    }

    throw new Exception("NotAFood!");
  }

Upvotes: 2

Views: 802

Answers (4)

Marko Topolnik
Marko Topolnik

Reputation: 200158

Mostly you are confusing classes with their instances. The instanceof operator, as its name says, verifies that an object is an instance of a class, not that a class is a subclass of another. Your particular problem would be solved most elegantly by resorting to reflection:

public static <T extends Meal> T createMeal(Class<T> c) {
  try { return c.newInstance(); }
  catch (Exception e) { throw new RuntimeException(e); }
}

For example, if you want a Burger, you call

Burger b = createMeal(Burger.class);

But, if you really wanted just another instance of the same type as an instance that you already have, then the code would be

public static Meal createMeal(Meal x) {
  try { return x.getClass().newInstance(); }
  catch (Exception e) { throw new RuntimeException(e); }
}

Upvotes: 4

Horonchik
Horonchik

Reputation: 477

I guess you are referring to reflection. look at this link http://java.sun.com/developer/technicalArticles/ALT/Reflection/

import java.lang.reflect.*;

   public class constructor2 {
      public constructor2()
      {
      }

  public constructor2(int a, int b)
  {
     System.out.println(
       "a = " + a + " b = " + b);
  }

  public static void main(String args[])
  {
     try {
       Class cls = Class.forName("constructor2");
       Class partypes[] = new Class[2];
        partypes[0] = Integer.TYPE;
        partypes[1] = Integer.TYPE;
        Constructor ct 
          = cls.getConstructor(partypes);
        Object arglist[] = new Object[2];
        arglist[0] = new Integer(37);
        arglist[1] = new Integer(47);
        Object retobj = ct.newInstance(arglist);
     }
     catch (Throwable e) {
        System.err.println(e);
     }
  }

}

Upvotes: 2

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Try out the Class's class method : static Class<?> forName(String class_name)

for returning the object of the class that matches the instanceof condition.

Upvotes: 1

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

If I understand correctly you want something like this?

if(f.getClass().isAssignableFrom(HotDog.class))
   return new HotdogObject();

Upvotes: 2

Related Questions