Question

I don't want to hardwire the class name and use the instanceOf but dynamically identifying the class

Lets say I have

// add fragments
mFragments = new ArrayList<Fragment>();
mFragments.add(Fragment.instantiate(this, class1.class.getName()));
mFragments.add(Fragment.instantiate(this, class2.class.getName()));

public class class1 extends SherlockListFragment{
   public static final String TAG = "class1";
}

All classes have the extends SherlockActivity or SherlockListFragment so they have a common base class Fragment. How can I now when iterating trough the array get e.g. the static tag or something else that will identify the Class without using instanceOf. I have some ides but wanted to get some input so I can learn

 public static final String TAG = "class1"
Était-ce utile?

La solution

Add a method in the base class which returns the tag. Then iterate over your structure and get the tag for each subtype.

public class SherlockListFragment{
    public String getTag(){ 
        return TAG;
    }
}

You don't need to determine the exact subtype of class. Any time you start encountering odd problems like this, I'd suggest reworking design first rather than finding a work around.

Autres conseils

Have a method in your Fragment class as below:

public class Fragment {
    ...
    public String getTag() {
       return this.getClass().getCanonicalName();
    }
}

public class Fragment1 extends Fragment {
   ...
}

public class Fragment2 extends Fragment {
   ...
}

Now, I tested it using simple code below:

Fragment f = new Fragment1();
Fragment f1 = new Fragment2();

System.out.println(f.getTag());
System.out.println(f1.getTag());

Which gives output:

Fragment1
Fragment2
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top