I am wondering how to use java reflection with kotlin.
Let’s consider something like this:
final Format format = new DecimalFormat(“#.00”);
final Number number = 1.2;
// Format.format(Object) using reflection (maybe those objects are on a different class loader)
final String formatted = (String)format.getClass().getMethod(“format”, Object.class).invoke(format, number);
So far I have this:
val format: Format = DecimalFormat(“#.00”)
val number: Number = 1.2
val formatted = format.javaClass.getMethod(“format”, <Missing piece>)?.invoke(format, number) as String
As you can see, I am missing a piece: How to translate the Object.class
bit. I can’t use number.javaClass
, because it won’t give me Object.class
.
Is there a syntax for Object.class
?
I ran into the problem before with android intents:
final Intent intent = new Intent(activity, OtherActivity.class);
activity.startActivity(intent);
In this particular case, I cannot get an instance of OtherActivity
to call .javaClass
on.
The workaround is to create the Intent like this:
final Intent intent = new Intent(null);
intent.setComponent(activity.getPackageName(), className);
This is only possible because this setComponent
method exists and is public.