JAvaインスタンスタイプを動的に取得し、インスタンスを作成


Javaプログラミングではよくこのような問題に遭遇します
1、すでに1つのクラスのインスタンスがあって、このインスタンスがあるクラスの対象かどうかを判断する.
2.クラスのインスタンスが既知であり、特にこのインスタンスタイプがダイナミックである可能性がある場合に、このインスタンスタイプと同じオブジェクトを作成したい.
 
1つのキーワードと2つの関数について説明します.
instanceofキーワードは、参照タイプ変数が指すオブジェクトがクラス(またはインタフェース、抽象クラス、親クラス)のインスタンスであるかどうかを判断するために使用されます.
例はnewInstanceを参照してください.
 
getClass() Returns the runtime class of this Object.インスタンスの実行時タイプを返します.
サンプルコードは次のとおりです.
		String stringInstance = new String();
		Object objectInstance = stringInstance.getClass().newInstance(); 
		System.out.println(objectInstance.getClass().getName());
		Object objectInstance2 = new Object(); 
		System.out.println(objectInstance2.getClass().getName());

 
出力結果:
java.lang.String
java.lang.Object
参照:http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#getClass()
 
newInstance() Creates a new instance of the class represented by this Class object.1つのclassの例を着ます
コードは次のとおりです.
		String stringInstance = new String();
		Object objectInstance = stringInstance.getClass().newInstance();  
		if (objectInstance instanceof Object)
			System.out.println("ob   Object  ");
		if (objectInstance instanceof String)
			System.out.println("ob   String  ");

 
出力結果:
 
obはObjectインスタンスです
obはStringの例です
参照先:
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance()
 
以上の二つの問題はいずれも解決した