Is it possible to bypass constructors when instantiating objects in Android - android

Do Android have any way to instantiate objects without calling any of its constructors?
In Java, Sun have sun.reflect.ReflectionFactory.getReflectionFactory().newConstructorForSerialization(), in .Net we have System.Runtime.Serialization.FormatterServices.GetUninitializedObject() but I was not able to find anything like that in the Android platform.

After looking into Android source code we found a way to achieve this by using ObjectInputStream#newInstance() static method.
private Object newInstanceSkippingConstructor(final Class clazz) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Method newInstance = ObjectInputStream.class.getDeclaredMethod("newInstance", Class.class, Class.class);
newInstance.setAccessible(true);
return newInstance.invoke(null, clazz, Object.class);
}

You can do this from native code with the JNI AllocObject function. See the JNI Spec. Calling out to native code is going to be more expensive than calling a no-op constructor, but probably cheaper than calling a constructor that throws an exception.
I don't know if there's another way to do it. Nothing is leaping out at me.

I don't believe so, however the Android platform does contain the Java Reflection API in java.lang.reflect.* so anything that is possible using the Java Reflection API is possible in Android

I found out a library that can handle OBJ init with constructor bypass
http://objenesis.org/index.html
And they have different methods for different APIs.
There is a slight difference in their API 17 and 18+ impl as in the current suggested answer. Also Android N+ is using something called Unsafe that should be implemented by new JVMs http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/

Related

None of the arguments can be called with the agruments supplied with Gson

I have started working with a Kotlin Multiplatform library, and I make use of Gson on the android side to do some processes. Since I know iOS does not have support for Gson, I decided to create an expected function called convertToJson which has a return type of a class. However when I have the actual implementation, I get the following error:
None of the arguments can be called with the arguments supplied
This occurs at this line of code:
actual fun convertFromJson(json:String): ClassName {
return Gson().fromJson(json, ClassName::class) // this is where the error lies
}
I also have an actual implementation of a function called convertToJson which does not give me an error, so I am wondering why the above mentioned convertFromJson function gives me an error.
Any help or advice will be highly appreciated.
Gson is implemented in java and its fromJson accepts an instance of java.lang.Class as the argument, so you should replace ClassName::class with ClassName::class.java, because the former gives you an instance of kotlin.reflect.KClass.

LifecycleObserver produce exception with methods that use newer APIs

My ViewModel class implements LifecycleObserver.
When I call fragment.lifecycle.addObserver(this) it produces exception.
Caused by: java.lang.IllegalArgumentException: The observer class has some methods that use newer APIs which are not available in the current OS version. Lifecycles cannot access even other methods so you should make sure that your observer classes only access framework classes that are available in your min API level OR use lifecycle:compiler annotation processor.
Strange, that firstly it was working fine, but not long ago this exception has appeared. I've found, that audioFocusRequest is cause of this bug.
private val audioFocusRequest by lazy {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setOnAudioFocusChangeListener(this)
.build() else throw RuntimeException("Can't be done for Android API lower than 26")
}
Does anybody know how it can be fixed?
UPD
Tried to use annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version", but got compilation error:
(decided to paste screenshot, because whole logs are quite big)
UPD 2
At the end I've decided to delete audioFocusRequest field and to use old deprecated method - requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) instead of recommended requestAudioFocus(#NonNull AudioFocusRequest focusRequest)
It helped me to make code working again, so it can be solution. But I didn't find answer - why this problem had appeared. It strange because code used to be working before.
So problem has been solved but question still stays unanswered
Try to use kapt "androidx.lifecycle:lifecycle-compiler:2.0.0"
The class which implements LifecycleObserver has some method, which has parameters with type that only exist for higher APIs.
Your variables (i guess) and function parameters must exist on all APIs even function is not called (maybe this is requirement for classes who implement LifecycleObserver).
A possible solution is to change function parameter type to Any (kotlin) or Object (Java) and cast it to appropriate type inside function.
I have to remove this set method on SpinnerView: lifecycleOwner = viewLifecycleOwner
I was able to fix this by moving the offending methods into another class, but still called from my LifecycleObserver. After reading the error message again:
Caused by: java.lang.IllegalArgumentException: The observer class has some methods that use newer APIs which are not available in the current OS version. Lifecycles cannot access even other methods so you should make sure that your observer classes only access framework classes that are available in your min API level OR use lifecycle:compiler annotation processor.
It seems as though no methods or objects are allowed in the class extending LifecycleObserver if they don't exist in the device's OS, even if they are wrapped in an SDK version check and never accessed.

Has MatrixCursor implementation within Android P changed?

Recently I have observed a large number of crashes for an app that I maintain when the Android P developer preview is used.
Diving (deep) into the project's code, I have found the problem method to be the following:
public static <T> T get(MatrixCursor cursor, int column) {
try {
cursor.moveToFirst();
Method get = MatrixCursor.class.getDeclaredMethod("get", int.class);
get.setAccessible(true);
return (T) get.invoke(cursor, column);
} catch (Exception e) {
throw new IllegalArgumentException("Android has changed the implementation of MatrixCursor?!");
}
}
From what I understand, this code is used to retrieve a custom object from the MatrixCursor directly, rather than a primitive type, byte array or String. There has previously been a private method within MatrixCursor that performs this internally, and it is this method that we access through reflection.
Needless to say, there's a number of issues with this approach. As far as I am aware, reflection to access private APIs is a feature that Android advises heavily against. Nevertheless, until the Android P preview, this seems to have been working as expected.
This leads me to raise the following questions:
Has MatrixCursor's implementation changed or is reflection totally deprecated as of Android P?
Sadly, I am not 100% clued up on what alternatives I have to avoid this issue. Any suggestions for that are greatly appreciated, is there a Cursor that can be used to store custom objects?
Yes, something has changed.
No, the underlying implementation of MatrixCursor has likely not changed.
What has changed is that Android P is introducing restrictions on non-public members of SDK classes. Attempting to use private fields or methods on SDK classes (whether by direct invocation, reflection, or JNI) will result in a crash.
If you run the code in question on a device running P and look at the logcat output, you should see a message similar to this:
Accessing hidden field Landroid/os/Message;->flags:I (light greylist, JNI)
I highly encourage you to fully read the linked documentation on these restrictions for the full context and for more information on how you can handle it.
One option (which you should do ASAP if needed!) is to file a bug so the Android team knows that this is a method you use and does not have a public alternative. If you do this before the release of Android P, there is a much better likelihood that the team will either create a public alternative for this method or allow you to continue to access that method in P.

Xamarin LocationManager.RequestSingleUpdate always throws IllegalArgumentException

For some reason whenever I implement ILocationListener and implement the necessary interface methods this call always crashes on me:
LocMgr.RequestSingleUpdate(provider, this, null);
It throws java.lang.IllegalArgumentException: invalid listener: null although it's obviously impossible for this to be null. Does anyone have any suggestions on how to deal with this?
There were two issues here.
I needed to inherit from Java.Lang.Object
I needed to make sure I wasn't providing new implementations of Dispose or Handle.
Once I removed these the function call worked as expected.

Unit testing: NoSuchMethodError while calling Notification.setLatestEventInfo()

Feel free to improve the title I'm a little uncreative in this special case.
I am implementing a unit test for checking notifications, this is hardly possible I know, but I want to check how far I can automatism it.
I cannot test this simple line of code:
Notification test = new NotificationCompat.Builder(context).build();
The reason is stupid and simple in one. This code here will been executed internally:
public Notification build(Builder b, BuilderExtender extender) {
Notification result = b.mNotification;
result.setLatestEventInfo(b.mContext, b.mContentTitle,
b.mContentText, b.mContentIntent);
[...]
I'm getting this exception:
Caused by: java.lang.NoSuchMethodError: android.app.Notification.setLatestEventInfo(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Landroid/app/PendingIntent;)V
at android.support.v4.app.NotificationCompat$NotificationCompatImplBase.build(NotificationCompat.java:479)
at android.support.v4.app.NotificationCompat$Builder.build(NotificationCompat.java:1561)
It is not hard to guess that the Google guys call here a method which was removed (or more properly annotated with #hide) in the Android Marshmallow SDK. I have verified it that call is missing the the newest documentation, but it was introduced in API 1 AFIK.
How can I work around that?
Things I tried and got stuck:
Overriding the callback, and mock that method without invoking that call:
I got it managed to get that Class<?> with the callback, but with which method I can override a hole method? I mean I need to patch the call it I cannot just mock it.
Injecting that call, but how? I can just override it and not adding it.
Suppressing the call with:
PowerMockito.spy(Notification.class);
PowerMockito.suppress(PowerMockito.method(Notification.class, "setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class));
Does not work ether since I try to kick a non existing method.
Change the target SDK for this test, but how can I do it?
The solution is easier than expected. I missed that by default Build.VERSION.SDK_INT has the value 0 since it cannot read the real value. So that support library calls it on just that platforms where this method exists.
With the help of this answer. I just had to add this code:
setFinalStatic(Build.VERSION.class.getDeclaredField("SDK_INT"), 23);
And my the codes works.
Well it still crashes somewhere else, but the notification is created. Wohoo!
And the actual function:
public static void setFinalStatic(Field field, Object newValue) throws IllegalAccessException, NoSuchFieldException
{
field.setAccessible(true);
// remove final modifier from field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}

Categories

Resources