import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String className = scanner.next(); Base obj = (Base) Class.forName(className).newInstance(); System.out.println(getClassName(obj)); } } public static String getClassName(Base obj) { //write your code here...... if(obj instanceof Base) { return obj.toString(); } else if(obj instanceof Sub1) { return obj.toString(); } else if(obj instanceof Sub2) { return obj.toString(); } return "Object"; } } class Base { public String toString() { return "Base"; } } class Sub1 extends Base { public String toString() { return "Sub1"; } } class Sub2 extends Base { public String toString() { return "Sub2"; } }
- instanceof运算符判断obj是否属于右边类所创建对象,instanceof是Java的保留关键字。
a instanceof A
2.传入的是一个实例,我们对这个实例调用getClass().getName()即可