Remapping in ByteBuddy Advice classes - byte-buddy

ByteBuddy has net.bytebuddy.jar.asm.commons.Remapper which allows e.g. runtime shading by using a classloader which transforms and remaps classes during loading. But I have a problem with remapping type references in ByteBuddy Advice classes. I assume it happens because BB does not actually load them as classes, but merely uses getResourceAsStream or similar to get byte array of the Advice class files.
So, question: how can I supply a Remapper for Advice classes?

You think about locating advice classes? You can supply an optional argument of type ClassFileLocator which is responsible for finding a class file for a given class. You'd need to look up a .class file with a different name or write a delegator that adjusts the class name before passing on to a different class file locator.

Related

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.

How to organize Kotlin extension methods

Let's say I have a few extension methods for "MyClass".
My question is, what's the best practice to organize/store these methods?
Should they be simply put into a "MyClassExtensions" Kotlin file?
I have tried to encapsulate these methods within a class, but after importing the class I couldn't seem to figure out how to use/access the extension methods.
Edit:
For clarification, I was not asking for help what to call a file that contains extension methods. I was asking about best practices/approaches to store/organize such methods. Ie. should they be simply put into kotlin files, or should they be encapsulated in a class. I am coming from a Java background, so I'm used to store stuff in classes.
As far as I am concerned, you should put them into a utility file, as you did in Java code base before.
But mention, you no longer need to put them into a class. Top-level functions are the best choice.
You can refer to the kotlin standard library or some open source projects like anko, those would be good examples.
In my case, I put extensions of one class into a file which have the same name of the original file in another package, and use
#JvmMultifileClass
to reduce the number of generated class files.

Better to add method to pre-defined class or make subclass?

Say you want to add a lengthOfFirstLine method to the predefined File class. Is it a better practice to modify the existing class, or make a new class that extends the File class with your new method?
EDIT -- Specifically, the situation is that a class is lacking one method in particular. I don't want to completely change the class, but rather augment it with that method.
It depends if the method is applicable to all elements of the class File. For instance, lengthOfFirstLine doesn't apply to binary files, so probably it doesn't belong in a generic File class, but if your class only represent text files, then it should go there.
For .NET languages, there's also the option of using extension methods. This way you don't have to "dirty up" a class by adding helper/utility methods to it, and no inheritance is required as well - you add functionality to a class by simply adding a using statement to your code.
Agree with Luis and Lester. If you are using .Net the extension methods are the way to go for this sort of functionality. But you should try not add LengthOfFirstLine to a base class if you can open all sorts of files such as binary files. You would sub class it to a FileClass and add the method to that.
Remember that the extension methods in .Net are syntactic sugar anyway. You can simulate it in your own language using Static classes and methods. This is what .Net does under the covers anyway.
For example have a static FileHelpers class and have various static helper methods on it. The first parameter for each of these static methods would be the File class. So you could call this using FileHelpers.GetLengthOfFirstLine(myOpenedFile)

FxCop, compose list of callers from dependent assembly

I'm building a couple of customs FxCop rules and one of the rules needs to enforce that a constructor is called in specific methods. For that, I need to create a list of callers, to that specific constructor, prior to performing the actual test. How is this possible? Is there some kind of handle to acquire a list of all loaded assemblies in the ApplicationDomain, where I can iterate through the classes and find the constructor Method object? Ideally the list of callers should be composed in the BeforeAnalysis method.
The Microsoft.FxCop.Sdk.CallGraph.CallersFor(Method) method may give you what you want. However, the general approach you seem to be describing is rarely a good idea because it would typically assign the problems to the wrong target. For example, in the scenario you describe, it would presumably be desirable to attribute the problems to the methods that should but do not contain the target contructor call. However, if your analysis target is the constructor, the detected problems will be attributed to the constructor rather than the methods that should have called it.
I think I haven't explained the question very well, but I see your point.
I have 3 different assemblies and for certain method calls from one assembly to another, I need to ensure that a benchmark constructor invoked. The benchmark class resides in a 4th assembly. Now my problem was that only VS2010 only loads one target assembly for analysis and when I used the CallGraph to construct the a list of methods calling the constructur, it would not find any. When Invoking FxCopCmd.exe manually I could just add the dependent assemblies manually with the /file: parameter.
My solution is to load the different assemblies manually (not relying on the loaded assembly in RuleUtilities.AnalysisAssemblies and contruct the list of callers in the BeforeAnalysis method.
RuleUtilities.GetAssembly(
RuleUtilities.AnalysisAssemblies
.First().Directory + "\\" + additionalAssemblyFilename)
.Types.SelectMany(type => type.Members)
.Where(member => member.IsPublic)
.Where(CanBeCastedToMethod)
.Cast<Method>()
.SelectMany(CallGraph.CallersFor);
With this approach I can contruct a list of callers, for each of the assemblies and for the benchmark class constructor. Works perfectly i VS2010.

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.