brinado 发表于 2013-2-4 20:23:14

我的理解 instanceof 用法

intanceof()方法主要用来判断变量的类型。
使用Object类型在构造器中,间接达到了多态的效果。
import java.lang.reflect.*;class ClassA{private int a;private String b;private int[] c;ClassA(Object temp){if(temp instanceof Integer){//判断输入的是整型a = Integer.parseInt(temp.toString());System.out.println("this is an <"+ temp.getClass().getName() +"> type. Integer value=" + a);}else if(temp instanceof String){//判断输入的是字符串b = temp.toString();System.out.println("this is a <"+ temp.getClass().getName() +"> type. String value=" + b);}else if(temp instanceof int[]){//判断输入的是整型数组int n = Array.getLength(temp);int[] c = new int;for(int i = 0;i < n; i++){c = Array.getInt(temp,i);}System.out.print("this is an <"+ temp.getClass().getName() +"> type. Int[]array value=");for(int i = 0;i < n; i++){System.out.print(c + ", ");}System.out.println();}}public static void main(String[] args){ClassA test1= new ClassA(12);ClassA test2= new ClassA("OK");int tmp[] = {1,2};ClassA test3= new ClassA(tmp);}}
我是初学者,还希望大家指教。
页: [1]
查看完整版本: 我的理解 instanceof 用法