Is it possible to modify an ASM's MethodVisitor object using Byte Buddy's high level API? - byte-buddy

I'm currently trying to learn how to create Kotlin Compiler Plugins for the JVM and I'd like to change a method's body as an example, the API requires to manipulate Java byte code using ASM API in order to make any changes to a class' components. The Kotlin compiler plugin provides this class where, if for example, you'd like to modify a class' method body, you'd need to override the newMethod function, which returns a MethodVisitor instance, which is the one that you'd need to manually modify using the ASM's API.
I would like to be able of doing so without having to write ASM instructions and I was wondering if there was a way to add instructions straight into a MethodVisitor object using Byte Buddy's high level API?
Many thanks!

Quite honestly, the API is a bit awkward since it does not follow the standard model of ASM where you wrap a class visitor and since it shades the ASM dependency which makes it non-compatible with any ASM user.
In Byte Buddy, you can register your own visitors so what you can do is to define a custom class in Byte Buddy, and before calling make, you'd register an AsmVisitorWrapper which delegates to the visitor Kotlin yields. You'd need to proxy all method calls from Kotlin's ASM namespace to Byte Buddy's ASM namespace, though what you can do using method handles.

Related

Expand type of parent-class member type

Let's consider the relationship below. For simplicity and to remain language agnostic I will use pseudocode:
class API
foo()
class FancyAPI -> API
bar()
class APIUser
APIUser(API api)
use()
api.foo()
class FancyAPIUser
FancyAPIUser(FancyAPI api)
use()
api.foo()
api.bar()
In a strongly typed language, at most you could have api be a pointer. One could assign the fancy api to the api pointer and cast it every time you want to use it.
In a weakly typed, dynamic language like python or JS you could just assign the new type and use is straight up, but all the code aid features like completion and linting would likely fail.
Another way for both types of langs would be to just keep separate references in the FancyAPIUser for FancyAPI and API.
I feel like there has to be a better way to do something like this. Anyone has suggestions?

How can deserialization of polymorphic trait objects be added in Rust if at all?

I'm trying to solve the problem of serializing and deserializing Box<SomeTrait>. I know that in the case of a closed type hierarchy, the recommended way is to use an enum and there are no issues with their serialization, but in my case using enums is an inappropriate solution.
At first I tried to use Serde as it is the de-facto Rust serialization mechanism. Serde is capable of serializing Box<X> but not in the case when X is a trait. The Serialize trait can’t be implemented for trait objects because it has generic methods. This particular issue can be solved by using erased-serde so serialization of Box<SomeTrait> can work.
The main problem is deserialization. To deserialize polymorphic type you need to have some type marker in serialized data. This marker should be deserialized first and after that used to dynamically get the function that will return Box<SomeTrait>.
std::any::TypeId could be used as a marker type, but the main problem is how to dynamically get the deserialization function. I do not consider the option of registering a function for each polymorphic type that should be called manually during application initialization.
I know two possible ways to do it:
Languages that have runtime reflection like C# can use it to get
deserialization method.
In C++, the cereal library uses magic of static objects to register deserializer in a static map at the library initialization time.
But neither of these options is available in Rust. How can deserialization of polymorphic objects be added in Rust if at all?
This has been implemented by dtolnay.
The concept is quite clever ans is explained in the README:
How does it work?
We use the inventory crate to produce a registry of impls of your trait, which is built on the ctor crate to hook up initialization functions that insert into the registry. The first Box<dyn Trait> deserialization will perform the work of iterating the registry and building a map of tags to deserialization functions. Subsequent deserializations find the right deserialization function in that map. The erased-serde crate is also involved, to do this all in a way that does not break object safety.
To summarize, every implementation of the trait declared as [de]serializable is registered at compile-time, and this is resolved at runtime in case of [de]serialization of a trait object.
All your libraries could provide a registration routine, guarded by std::sync::Once, that register some identifier into a common static mut, but obviously your program must call them all.
I've no idea if TypeId yields consistent values across recompiles with different dependencies.
A library to do this should be possible. To create such a library, we would create a bidirectional mapping from TypeId to type name before using the library, and then use that for serialization/deserialization with a type marker. It would be possible to have a function for registering types that are not owned by your package, and to provide a macro annotation that automatically does this for types declared in your package.
If there's a way to access a type ID in a macro, that would be a good way to instrument the mapping between TypeId and type name at compile time rather than runtime.

Qt Webkit Bridge: C++ access to JavaScript

I am using a QWebView and call to setHtml() to display some HTML/JavaScript pages. I am passing data updates using QWebFrame::evaluateJavaScript by passing it a QString containing a call to a JavaScript function (with arguments). After reading about the Qt WebKit Bridge I
feel like there should be a better way to do his. I see discussion of exposing Qt objects / functions in C++ to the JavaScript, but not the other direction. (I do not want the JavaScript to poll the C++ side for updates.) Is there a way to connect a JavaScript function as a slot to a Qt/C++ signal? (Or a similar pattern) I feel like I have looked through a lot of docs, posted questions (even the 'Similar Questions' as I type this), but have not seen examples of this. Appreciate any info, links or nudges in the right direction.
Use addToJavaScriptWindow object for exposing your C++ objects the Javascript tier:
page()->mainFrame()->addToJavaScriptWindowObject(QString("myObject"), myObject);
Check documentation here:
http://qt-project.org/doc/qt-4.8/qwebframe.html#addToJavaScriptWindowObject
That will expose your C++ myObject as "myObject".
Then, you can do exactly what you are looking for on your post, let's suppose myObject declares a signal in the following way:
signal:
mySignal(QString aParameter);
you can simply connect that signal to a slot on your web side as follows:
myObject.mySignal.connect(this, this.mySignalSlot);
In this case, mySignalSlot should have the same signature than mySignal declaration at the C++ class side (well, "same signature" would mean same number of parameters as javascript is not typed, so you won't need to declare a type for each of them).
What's really usefull here is to pass JSon objects. In case you need to pass big amount of data you can use base64 encoding. For images, QTWebKit supports natively QImage and QPixmap classes; these last two are natively encoded as complex javascript objects by QTWebKit Bridge engine.

Has Freemarker something similar to toolbox.xml-file of Velocity?

I have a Struts 1 application which works with Velocity as a template language. I shall replace Velocity with Freemarker, and am looking for something similar to 'toolbox.xml'-File from VelocityViewServlet. (there you can map names to Java Classes and, using these names it is possible to access methods and variables of various Java class in the Velocity template).
Does someone know, what is possible with Freemarker instead? So far I have found only information about the form beans...would be glad if someone can help....
For the utility functions and macros that are View-related (not Model-related), the standard practice is to implement them in FreeMarker and put them into one or more templates and #import (or #include) them. It's also possible to pull in TemplateDirectiveModel-s and TemplateMethodModelEx-es (these are similar to macros and function, but they are implemented in Java) into the template that you will #import/#inlcude as <#assign foo = 'com.example.Foo'?new()>.
As of calling plain static Java methods, you may use the ObjectWrapper's getStaticModels() (assuming it's a BeansWrapper subclass) and then get the required methods as TemplateMethodModelEx-es with staticModels.get("com.example.MyStatics"). Now that you have them, you can put them into the data-model (Velocity context) in the Controller, or pick methods from them in an #import-ed template, etc. Of course, you can also put POJO objects into the data-model so you can call their non-static methods.
The third method, which is not much different from putting things into the data-model is using "shared variables", which are variables (possibly including TemplateMethodModelEx-es and TemplateDirectiveModel-s) defined on the Configuration level.

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.