Allow object creation using SafeParcelUtil and add AutoSafeParcelable

This commit is contained in:
mar-v-in 2015-01-12 10:30:23 +01:00
parent 8eb274e499
commit 1c2e9644da
2 changed files with 54 additions and 0 deletions

View File

@ -0,0 +1,36 @@
package org.microg.safeparcel;
import android.os.Parcel;
import java.lang.reflect.Array;
public abstract class AutoSafeParcelable implements SafeParcelable {
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
SafeParcelUtil.writeObject(this, out, flags);
}
public static class AutoCreator<T extends SafeParcelable> implements Creator<T> {
private Class<T> tClass;
public AutoCreator(Class<T> tClass) {
this.tClass = tClass;
}
@Override
public T createFromParcel(Parcel parcel) {
return SafeParcelUtil.createObject(tClass, parcel);
}
@Override
public T[] newArray(int i) {
return (T[]) Array.newInstance(tClass, i);
}
}
}

View File

@ -5,13 +5,31 @@ import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class SafeParcelUtil {
private static final String TAG = "SafeParcel";
public static <T extends SafeParcelable> T createObject(Class<T> tClass, Parcel in) {
try {
Constructor<T> constructor = tClass.getDeclaredConstructor();
boolean acc = constructor.isAccessible();
constructor.setAccessible(true);
T t = constructor.newInstance();
readObject(t, in);
constructor.setAccessible(acc);
return t;
} catch (NoSuchMethodException e) {
throw new RuntimeException("createObject() requires a default constructor");
} catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException("Can't construct object", e);
}
}
public static void writeObject(SafeParcelable object, Parcel parcel, int flags) {
if (object == null)
throw new NullPointerException();