Skip to content

Commit

Permalink
Allow object creation using SafeParcelUtil and add AutoSafeParcelable
Browse files Browse the repository at this point in the history
  • Loading branch information
mar-v-in committed Jan 12, 2015
1 parent 8eb274e commit 1c2e964
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/org/microg/safeparcel/AutoSafeParcelable.java
Original file line number Diff line number Diff line change
@@ -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 changes: 18 additions & 0 deletions src/org/microg/safeparcel/SafeParcelUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,31 @@
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();
Expand Down

0 comments on commit 1c2e964

Please sign in to comment.