开发者

help requested understanding Java Reflection --> Android ParcelableContainer

开发者 https://www.devze.com 2023-02-12 06:08 出处:网络
I\'m, playing with the Android framework and try to get my mind deeper into Java. For This I read about Javas Generics and the Reflection API, while I\'m not understanding it really.

I'm, playing with the Android framework and try to get my mind deeper into Java. For This I read about Javas Generics and the Reflection API, while I'm not understanding it really. Because I'm a lazy Dev ;) I tried to write an 'Parcelable-Container' in which I can put ANY Object I wish to get it Parcelable without the need to implement this for every Object again using methods of Java Reflection.

I write a test method like these:

public <T> void writeClassInformations(T t){
        Class c = t.getClass();

        System.out.println("DeclaredFields: ");
        for (Field f : c.getDeclaredFields()){
            System.out.println(f.toGenericString());
        }
        System.out.println("Fields: ");
        for (Field f: c.getFields()){
            System.out.println(f.toGenericString());
        }
}

How can I get every member even if they are Objects or private Superclass members? And another Question: The output is like this:

public int hello.test.Testclass.myID

how I get the value of 'myID'?


ADD: I'm running in serious problems now. The Interface of Parcelable.Creator forces me to write a statement like: public static final Parcelable.Creator CREATOR = new Parcelable.Creator<ParcelableBox<?>>() Can I use ? somehow? Normally I use a constructor like ParcelableBox(E object). While it seems to me that I can't use Object methods on ? I even cannot pass it into a class variable like

public ParcelableBox<?> createFromParcel(Parcel source){  
  ...
  return new ParcelableBox<?&开发者_开发技巧gt;(); 
}

or ? myClass to use Reflection on it. Is this the end of javas reflection power? How can I get Class of ?


Reflection should be used sparingly, or not at all if it can be avoided, and especially not as a way to hack around good design principles. That being said, it can also be useful in certain situations ...

getDeclaredFields can return all types of fields while getFields only returns fields marked public.

The reason your test returns the same thing is that you're using getDeclaredFields in both statements.


how I get the value of 'myID'

You can only do that by operating on an instance of a class. E.g.,

T t = ...
Field field = t.getClass().getDeclaredField("myID");
field.setAccessible(true);
String value = (String) field.get(t);
0

精彩评论

暂无评论...
验证码 换一张
取 消