mirror of
https://github.com/moparisthebest/android_external_SafeParcel
synced 2024-12-04 14:32:17 -05:00
Allow object creation using SafeParcelUtil and add AutoSafeParcelable
This commit is contained in:
parent
8eb274e499
commit
1c2e9644da
36
src/org/microg/safeparcel/AutoSafeParcelable.java
Normal file
36
src/org/microg/safeparcel/AutoSafeParcelable.java
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
@ -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…
Reference in New Issue
Block a user