Browse Source

Allow object creation using SafeParcelUtil and add AutoSafeParcelable

master
mar-v-in 8 years ago
parent
commit
1c2e9644da
  1. 36
      src/org/microg/safeparcel/AutoSafeParcelable.java
  2. 18
      src/org/microg/safeparcel/SafeParcelUtil.java

36
src/org/microg/safeparcel/AutoSafeParcelable.java

@ -0,0 +1,36 @@ @@ -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);
}
}
}

18
src/org/microg/safeparcel/SafeParcelUtil.java

@ -5,13 +5,31 @@ import android.os.Parcel; @@ -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();

Loading…
Cancel
Save