Kotlin reflection error when calling function - reflection

I was trying to cast an unknown given object to the required class using kotlin primitives conversion methods like this:
private fun callSelfParser(origObj: Any, destClazz: KClass<*>): Any {
val methodName = when (destClazz) {
Int::class -> "toInt"
Char::class -> "toChar"
Long::class -> "toLong"
Byte::class -> "toByte"
Float::class -> "toFloat"
Short::class -> "toShort"
Double::class -> "toDouble"
Boolean::class -> "toBoolean"
else -> ""
}
val parsingMethod: KFunction<*>
try {
parsingMethod = origObj::class.functions.toList().first { it ->
it.name == methodName
}
} catch (e: NoSuchElementException) {
throw ObjectMapperEx("Element $origObj doesn't have a method for parsing to $destClazz")
}
return parsingMethod.call(origObj)!!
}
But I got the following exception when executing the .call():
Exception in thread "main" kotlin.reflect.jvm.internal.KotlinReflectionInternalError: Reflection on built-in Kotlin types is not yet fully supported. No metadata found for public open val length: kotlin.Int defined in kotlin.String[DeserializedPropertyDescriptor#1cbb87f3]
Can someone say whats wrong or, if there's another way to achieve my goal?

Related

Unable to open SQLite database from singleton object

I am able to open the database from within the main app activity using the following code, but once it's wrapped into a singleton object, it keeps throwing a null-object error:
object CommonClass {
fun openSQLDatabase(): SQLiteDatabase? {
var dbase: SQLiteDatabase? = null
try {
dbase = openOrCreateDatabase(
"dbfile.sqlite",
Context.MODE_PRIVATE, null
)
} catch (e: SQLException) {
println(e.message)
}
return dbase
}
}
I'm assuming that the main AppCompatActivity should be passing its context to the object in some way, but I've not been able to find a working model.
to Swayangjit
Android Studio highlights the Context.MODE_PRIVATE parameter and flags it as:
Type mismatch.
Required: SQLiteDatabase.CursorFactory?
Found: Int
But when I implement the AppCompatActivity to the singleton object and pass the Context.MODE_PRIVATE from the main activity, it runs but throws this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory)' on a null object reference
I believe the following will work :
object CommonClass {
fun openSQLDatabase(context: Context): SQLiteDatabase? {
var dbase: SQLiteDatabase? = null
if (dbase == null) {
try {
dbase = openOrCreateDatabase(context.getDatabasePath("dbfile.sqlite"), null)
} catch (e: SQLException) {
println(e.message)
}
}
return dbase
}
}
Note this assumes that you want the database in the default location i.e. data/data/the_package_name/databases/dbfile.sqlite
You could invoke/call it using something like :-
val mydb = CommonClass.openSQLDatabase(this)

RxAndroid operator retryWhen is invoked but does not resubscribe

API class using Retrofit
class interface TestApi {
#GET("/path/abc/xyz")
fun get(): Single
}
UseCase class
fun getResult(): Single {
return testApi.get()
.map{ response ->
val type = response.type
when(type){
null -> throw Exception()
else -> response
}
}
.retryWhen{ throwableHandler ->
throwableHandler.flatMap {
when(it) {
is Exception() -> Flowable.error(it)
else -> Flowable.timer(3,TimeUnit.SECONDS)
}
}
}
.timeout(60, TimeUnit.SECONDS)
}
MainClass.kt
usecase.getResult()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(onError = {Log.d(TAG,"Error")},
onSuccess = {Log.d(TAG,"Next")})
When app run :
If api return NULL, retryWhen() will be invoked then api is called again.
Event not timeout reached and api return Not NUL result -> onSuccess is called. This is correctly processing of retryWhen() operator in rxJava.
My Problem:
If I write some test method (to pretend API Retrofit) in MainClass.kt looks like below:
private fun testPretend(): Single<Animal> {
return Single.just(Animal)
}
MainClass.kt looks like:
testPretend()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(onError = {Log.d(TAG,"Error")},
onSuccess = {Log.d(TAG,"Next")})
So event retryWhen is invoked , testPretend() method is not called again.
What is the problem here?
And what is difference between Single return by testPrerend() and Retrofit API ?
The method testPretend() is not called again because the observable that it returned is what is being resubscribed to. If you want the method to be invoked again upon resubscription, you will need to do something like this:
Single.defer( () => testPretend() )
...
.retryWhen( ... )
...;
This will invoke testPretend() upon resubscription.

why the coroutine exception handler double the original exception?

I implements my own async, I can't process the exception in a right way. why?
val expected = IllegalStateException();
val it = async<Any> {
throw expected;
};
assert.that({ it.get() }, throws(equalTo(expected)));
// ^--- but it throws a IllegalStateException(cause = expected)
Source Code
interface Response<in T> {
suspend fun yield(value: T);
}
interface Request<out T> {
fun get(): T;
fun <R> then(mapping: (T) -> R): Request<R>;
}
private val executor: ExecutorService = ForkJoinPool(20);
fun <T> async(block: suspend Response<T>.() -> Unit): Request<T> {
return object : Request<T>, Response<T> {
#Volatile var value: T? = null;
var request: Continuation<Unit>? = block.createCoroutine(this, delegate {}).let {
var task: Future<*>? = executor.submit { it.resume(Unit); };
return#let delegate {
try {
val current = task!!;
task = null;
current.get();
} catch(e: ExecutionException) {
throw e.cause ?: e;
}
};
};
override fun <R> then(mapping: (T) -> R): Request<R> = async<R> {
yield(mapping(get()));
};
override fun get(): T {
return value ?: wait();
}
private fun wait(): T {
val it = request!!;
request = null;
it.resume(Unit);
return value!!;
}
suspend override fun yield(value: T) {
this.value = value;
}
};
}
inline fun <T> delegate(noinline exceptional: (Throwable) -> Unit = { throw it; }, crossinline resume: (T) -> Unit): Continuation<T> {
return object : Continuation<T> {
override val context: CoroutineContext = EmptyCoroutineContext;
override fun resumeWithException(exception: Throwable) {
exceptional(exception);
}
override fun resume(value: T) {
resume(value);
}
}
}
the strange behavior is comes from java. the ForkJoinTask#getThrowableException will rethrow exception for the given task:
Returns a rethrowable exception for the given task, if
available. To provide accurate stack traces, if the exception
was not thrown by the current thread, we try to create a new
exception of the same type as the one thrown, but with the
recorded exception as its cause. If there is no such
constructor, we instead try to use a no-arg constructor,
followed by initCause, to the same effect. If none of these
apply, or any fail due to other exceptions, we return the
recorded exception, which is still correct, although it may
contain a misleading stack trace.
which implies that if you don't want to rethrow exception for the give task you can make the exception constructor non-publicly, for example:
val exception = object: IllegalStateException(){/**/};
// ^--- its constructor only available in its scope

How do you share implementation details in a functional language like rust?

I sometimes find myself writing abstract classes with partial implementation in C#:
abstract public class Executor {
abstract protected bool Before();
abstract protected bool During();
abstract protected bool After();
protected bool Execute() {
var success = false;
if (Before()) {
if (During()) {
if (After()) {
success = true;
}
}
}
return success;
}
}
Notwithstanding the wisdom of such a control structure, how would I accomplish this (partial shared implementation) in a functional language like rust?
Using default methods on traits is one way (and will probably/hopefully be the idiomatic way in the future; until recently, the struct-with-closures method #Slartibartfast demonstrates was the only thing that actually worked):
#[allow(default_methods)];
trait Executable {
fn before(&self) -> bool;
fn during(&self) -> bool;
fn after(&self) -> bool;
fn execute(&self) -> bool {
self.before() && self.during() && self.after()
}
}
impl Executable for int {
fn before(&self) -> bool { *self < 10 }
fn during(&self) -> bool { *self < 5 }
fn after(&self) -> bool { *self < 0 }
// execute is automatically supplied, if it is not implemented here
}
Note that it is possible for an implementation of Executable to override execute at the moment (I've opened an issue about a #[no_override] attribute that would disable this).
Also, default methods are experimental and prone to crashing the compiler (yes, more so than the rest of Rust), but they are improving quickly.
I'm not within reach of a rust compiler, so forgive broken code.
On a functional side of things, you could make a struct that holds three functions and invoke them
struct Execution {
before: #fn() -> bool,
during: #fn() -> bool,
after: #fn() -> bool
}
fn execute (e: Execution) -> bool {
...
}
but once you have a function as a first class value, you could pass say, a list of boolean functions to check against instead of fixed three, or something else depending on what are you trying to achieve.
On a rust side of things, you can make it more "object oriented" by using traits
trait Executable {
fn execute(&self);
}
impl Execution {
fn execute(&self) {
...
}
}

Dynamically implement interface in Groovy using invokeMethod

Groovy offers some really neat language features for dealing with and implementing Java interfaces, but I seem kind of stuck.
I want to dynamically implement an Interface on a Groovy class and intercept all method calls on that interface using GroovyInterceptable.invokeMethod. Here what I tried so far:
public interface TestInterface
{
public void doBla();
public String hello(String world);
}
import groovy.lang.GroovyInterceptable;
class GormInterfaceDispatcher implements GroovyInterceptable
{
def invokeMethod(String name, args) {
System.out.println ("Beginning $name with $args")
def metaMethod = metaClass.getMetaMethod(name, args)
def result = null
if(!metaMethod)
{
// Do something cool here with the method call
}
else
result = metaMethod.invoke(this, args)
System.out.println ("Completed $name")
return result
}
TestInterface getFromClosure()
{
// This works, but how do I get the method name from here?
// I find that even more elegant than using invokeMethod
return { Object[] args -> System.out.println "An unknown method called with $args" }.asType(TestInterface.class)
}
TestInterface getThisAsInterface()
{
// I'm using asType because I won't know the interfaces
// This returns null
return this.asType(TestInterface.class)
}
public static void main(String[] args)
{
def gid = new GormInterfaceDispatcher()
TestInterface ti = gid.getFromClosure()
assert ti != null
ti.doBla() // Works
TestInterface ti2 = gid.getThisAsInterface()
assert ti2 != null // Assertion failed
ti2.doBla()
}
}
Returning the Closure works fine, but I couldn't figure a way to find out the name of the method being called there.
Trying to make a Proxy to the this reference itself (so that method calls will call invokeMethod) returns null.
You could use the Map coercion feature of Groovy to dynamically generate a Map that represents the given interface:
TestInterface getMapAsInterface() {
def map = [:]
TestInterface.class.methods.each() { method ->
map."$method.name" = { Object[] args->
println "Called method ${method.name} with ${args}"
}
}
return map.asType(TestInterface.class)
}
To complete the response of Christoph, as stated by this page, you can implement an interface with a closure. For example:
def map = [doBla: { println 'Bla!'}, hello: {world -> "Hello $world".toString()}] as TestInterface
map.hello 'Groovy' // returns 'Hello Groovy'

Resources