How to use Kotlin to inspect all calls of a particular function? - kotlin

In our codebase we have a third-party library method that behaves in an unexpected manner when you pass null to it. To help prevent misuse of the method, I would like to write a test that walks through the codebase, finds all calls to the method, and makes sure the type of the single parameter passed in is not nullable.
Is this possible using Kotlin reflection? Is this possible in Kotlin at all? I can get to the point where I list out all the functions in the codebase, but am stumped on how to continue!

Related

Kotlin: How can I determine the extension function exists

Suppose I have a function (in Kotlin over Java):
fun <E> myFun() = ...
where E is a general type I know nothing about. Can I determine within this function whether there exists an extension function E.extFun()? And if so, how?
I very much doubt this is possible.
Note that extension functions are resolved statically, at compile time.
And that they're dependent on the extension function being in scope, usually via a relevant import.  In particular, it's possible to have more than one extension function with the same name for the same class, as long as they're defined in different places; the one that's in scope will get called.
Within your function, you won't have access to any of that context.  So even if you use reflection (which is the usual, and much-abused, ‘get out of jail free card’ for this sort of issue), you still won't be able to find the relevant extension function(s).  (Not unless you have prior knowledge of where they might be defined — but in that case, you can probably use that knowledge to come up with a better approach.)
So while I can't say for certain, it seems highly unlikely.
Why do you want to determine this?  What are you trying to achieve by it?

vb pass name of function using intellisense

I'm tying to implement a novel way of overriding functions based on which DLLs I have loaded. In this model, I have a list of class instances from First = Highest Priority to Last = Lowest priority.
Any of those classes may implement a Hook function or callback. I'm currently at the stage where I can pass a string to a function, and then call it - my library convention looks like this:
Dim hookclasses as HooksList
Dim callable as Object
hookclasses.Add(new ClassA)
hookclasses.Add(new ClassB)
'... etc.
if hookclasses.Has("MyHookFunction", callable) then
callable.MyHookFunction()
end if
This all works, but I'd like to reduce typos by leveraging Intellisense. I've already thought of popping the strings into a class containing constant strings, so I'm after something better than that.
Ideally I'd like to have a fallback class that implements all of the hook functions (even if it simply returns), and if the language supported it, I'd like to do the following:
if hookclasses.Has(NameOf(FallbackClass.MyHookFunction), callable) then ...
Clearly there is no 'NameOf' operator, and I don't know how to write a NameOf function.
Is this possible?
Thanks.
Check this article nameOf (C# and Visual Basic reference)
https://msdn.microsoft.com/en-us/library/dn986596.aspx
It does exactly what you want. And before that String Litterals were almost the only option.
Edit :
Question was : "Clearly there is no 'NameOf' operator, and I don't know how to write a NameOf function."
If I understand your problem right, you have a list of classes that you fetched from dynamically loaded DLL, point is you don't know if a class implements all of the hooks or only a few.
If you use an interface, like IHookable and put all the hook functions in there, it means all the DLL have to implement all the hook functions, which is not what you want.
And (if I understand it properly) if the first class in list does not implement the hook, you check the second one and so on. So with an interface you wouldn't know if the hook is implemented or not.

Should I put assertions inside object's methods or writing and calling a check representation fuction is enough?t

I wonder if writing a check representation function for an object and calling it while testing is enough to check the object's internal state corectness or should I also put assertions inside methods? Or maybe I should only use assertions inside methods and just don't include them in production version to not slow my app down?

How does Groovy work in a dynamic way?

I have built a small compiler, for a statically typed language. After understanding how a static language works, I'm having trouble getting my head into dynamic languages like groovy.
While constructing my compiler, I know that once I generate the machine level-code there is no way of changing it! (i.e its run-time).
But how does Groovy do this magical stuff like inferring type in statements like:
def a = "string"
a.size()
As far as I'm concerned, groovy has to find the type a is of string before running the line a.size(). It seems that it does so in compile time (while constructing AST)! But the language is called dynamic.
I'm confused, kindly help me figure out.
Thanks.
Groovy doesn't simply "call" a method, but dispatches it through the meta-object protocol. The method invocation is sent as a message to the object, which can respond to it or not. When using dynamic typing, it doesn't matter the object type, only if it responds to that message. This is called duck typing.
You can see it (though not easily) when you decompile Groovy code. You can compile using groovyc and decompile using other tool. I recommend jd-gui. You won't see the method being called explicitly, because of Groovy's method caching (it is done this way to achieve Groovy's neat performance).
For a simple script like:
def a = "abcdefg"
println a.substring(2)
This will be the generated code:
CallSite[] arrayOfCallSite = $getCallSiteArray(); Object a = "abcdefg";
return arrayOfCallSite[1].callCurrent(
this, arrayOfCallSite[2].call(a, Integer.valueOf(2))); return null;
And the method call is "dispatched" to the object, not called directly. This is a similar concept to Smalltalks and Ruby method dispatch. It is because of that mechanism that you can intercept methods and property access on Groovy objects.
Since Groovy 2, Groovy code can be statically compiled, thus acting like your compiler.

What is the use of reflection in Java/C# etc [duplicate]

This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.