简体   繁体   English

如何在 Java 中执行 object.getClass().getName()

[英]How to do object.getClass().getName() in Java

I want to implement to classes, Food and FoodFactory such that they satisfies the following input and output.我想实现类, FoodFoodFactory ,以便它们满足以下输入和输出。

//Input:
FoodFactory ff = new FoodFactory();
Food f1 = ff.getFood('Fruit');
Food f2 = ff.getFood('Meat');
f1.serveFood(); 
f2.serveFood();
System.out.println(f1.getClass().getSuperClass().getName());
System.out.println(f1.getClass().getName());
System.out.println(f2.getClass().getName());

//Output:
I'm serving Fruit
I'm serving Meat
Food
Fruit
Meat

Suppose we have the following constraints:假设我们有以下约束:

  1. Only write the two classes Food and FoodFactory只写FoodFoodFactory两个类
  2. Only java.util.* is allowed只允许 java.util.*

What I don't know is how to make getClass().getName() working in different situation.我不知道如何让getClass().getName()在不同的情况下工作。 I can only get FoodFactory .我只能得到FoodFactory

Thanks!谢谢!

Looks like you are practicing some OO with Java .看起来您正在使用 Java 练习一些 OO。 It's better if you ask a doubt instead the full scenario.如果你问一个疑问而不是完整的场景会更好。

However I will paste a sample here and you can ask any doubt you have.但是,我将在此处粘贴一个示例,您可以提出任何疑问。 FoodFactory class below, note that for a name you will get the right Object.下面的 FoodFactory 类,请注意,对于名称,您将获得正确的 Object。

public class FoodFactory {

  public Food getFood(String food) {

    if ("Meat".equals(food)) {
      return new Meat();
    } else if ("Fruit".equals(food)) {
      return new Fruit();
    }
    throw new IllegalArgumentException("No food found with name " + food);
  }
}

Both your Food classes should be created, in this case Meat and Fruit.应该创建两个 Food 类,在本例中为 Meat 和 Fruit。

public class Meat extends Food {
}

Your Food will print message based on current classes.您的食物将根据当前课程打印消息。 Others will inherit the behavior.其他人将继承该行为。

public class Food {
  public void serveFood() {
    System.out.println("I'm serving " + getClass().getSimpleName());
  }
}

Then you can simply run your scenario and note that getClass will run for right hierarchy.然后您可以简单地运行您的场景并注意 getClass 将针对正确的层次结构运行。

FoodFactory ff = new FoodFactory();
Food f1 = ff.getFood("Fruit");
Food f2 = ff.getFood("Meat");
f1.serveFood();
f2.serveFood();
System.out.println(f1.getClass().getSuperclass().getSimpleName());
System.out.println(f1.getClass().getSimpleName());
System.out.println(f2.getClass().getSimpleName());

Try to play with it and understand.试着玩弄它并理解它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM