2つのクラスがあるとします
class parentClass{
String myElement;
}
class childClass extends parentClass{
String notMyElemtent;
}
ここで、クラス childClass のオブジェクトがあるとします。そのオブジェクトの myElement が元々parentClassに属していることをプログラムで伝える方法はありますか??
あなたは反射でそれを行うことができます。obj.getClass().getField("myElement") を使用して、フィールドを表す Field オブジェクトを取得します。これで、 MemberインターフェイスのgetDeclaringClass()メソッドを使用して、実際にこのメンバーを宣言するクラスまたはインターフェイスを取得できます。だから、このようなことをしてください
childClass obj = new childClass();
Field field = obj.getClass().getField("myElement");
if (field.getDeclaringClass().equals(parentClass.class)) {
// do whatever you need
}
そのオブジェクトの myElement が元々parentClassに属していることを伝える方法はありますか?
はい、リフレクションを使用してスーパー クラスのフィールドを調べることができます。
コードでは、これは次のようになります。
public static boolean belongsToParent(Object o, String fieldName) {
Class<?> sc = o.getClass().getSuperclass();
boolean result = true;
try {
sc.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
result = false;
}
return result;
}
public static void main(String[] args) {
childClass cc = new childClass();
System.out.println("myElement belongs to parentClass: " +
belongsToParent(cc, "myElement"));
System.out.println("notMyElemtent belongs to parentClass: " +
belongsToParent(cc, "notMyElemtent"));
}
出力:
myElement belongs to parentClass: true
notMyElemtent belongs to parentClass: false
さて、getDeclaredField(name)
クラスの使用、そしてそこにない場合は、そのスーパークラスなどを見てみてください。複数レベルの継承に対応:
Class<?> clazz = childClass.class;
do {
try {
Field f = clazz.getDeclaredField(fieldName);
//there it is! print the name of the super class that holds the field
System.out.println(clazz.getName());
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
} while (clazz != null);
import java.lang.reflect.Field;
public class Test4 {
public static void main(String[] args){
Child child = new Child();
System.out.println(getDeclaringClass(child.getClass(), "value"));
}
public static String getDeclaringClass(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
} catch (NoSuchFieldException e) {
if(clazz.getSuperclass() != null){
return getDeclaringClass(clazz.getSuperclass(), name);
}else{
return null;
}
}
return clazz.getName();
}
}
class Parent {
String value = "something";
}
class Child extends Parent {
}