What is the ByteBuddy recipe for building an upper-bounded wildcard? - byte-buddy

I know some of this, but not all of it. Most notably, I am aware of TypeDescription.Generic.Builder but I have a very specific question about it.
Suppose I want to build Supplier<? extends Frob<X>>.
Suppose further that all I know I have is a TypeDefinition for the parameter, but I don't know what it represents (in the example above it would represent Frob<X>). That is, I don't know whether the TypeDefinition I have is a class, a parameterized type, a generic array type, a type variable, a wildcard, or anything else; I just know it's a TypeDefinition.
Obviously if I wanted to make Supplier<Frob<X>>, I could just do:
TypeDescription.Generic.Builder.parameterizedType(TypeDescription.ForLoadedType.of(Supplier.class),
myTypeDefinition)
.build();
…assuming I haven't made any typos in the snippet above.
How can I make an upper-bounded wildcard TypeDefinition out of an existing TypeDefinition suitable for supplying as the "parameterized" part of a parameterized type build? Is there an obvious recipe I'm overlooking, or is this a gap in the builder's DSL?
(I'm aware of the asWildcardUpperBound() method on TypeDescription.Generic.Builder, but that presumes I have a builder to work with, and in order to "bootstrap" such a builder I would need to give it a TypeDescription at the very least. But I don't have a TypeDescription; I have a TypeDefinition which might be parameterized, and I don't want to use asErasure().)
(I'm sort of looking for a way to do TypeDescription.Generic.Builder.parameterizedType(myTypeDefinition).asWildcardUpperBound().build(), but I can't obviously do that.)
There does seem to be TypeDescription.Generic.OfWildcardType.Latent::boundedAbove but I can't tell if that's supposed to be an "internal use only" class/method or not.

Such an API was indeed missing. I added an API in today's release (1.11.5) to translate an existing generic type description to a builder what allows transformations to arrays or wildcards. The API is TypeDescription.Generic.Builder.of which accepts a loaded or unloaded generic type description.

Related

From a ByteBuddy-generated method, how do I set a (public) instance field in an object received as an argument to the return value of a MethodCall?

I am generating a class in ByteBuddy.
As part of one method implementation, I would like to set a (let's just say) public instance field in another object to the return value of a MethodCall invocation. (Keeping the example public means that access checks etc. are irrelevant.)
I thought I could use MethodCall#setsField(FieldDescription) to do this.
But from my prior question related to this I learned that MethodCall#setsField(FieldDescription) is intended to work only on fields of the instrumented type, and, looking at it now, I'm not entirely sure why or how I thought it was ever going to work.
So: is there a way for a ByteBuddy-generated method implementation to set an instance field of another object to the return value of a method invocation?
If it matters, the "instrumented method" (in ByteBuddy's terminology) accepts the object whose field I want to set as an argument. Naïvely I'd expect to be able to do something like:
MethodCall.invoke(someMethod).setsField(somePublicField).onArgument(2);
There may be problems here that I am not seeing but I was slightly surprised not to see this DSL option. (It may not exist for perfectly good reasons; I just don't know what they would be.)
This is not possible as of Byte Buddy 1.10.18, the mechanism was originally created to support getters/setters when defining beans, for example. That said, it would not be difficult to add; I think it would even be easiest to allow any custom byte code to be dispatched as a consumer of the method call.
I will look into how this can be done, but as a new feature, this will take some time before I find the empty space to do so. The change is tracked on GitHub.

avoid exposing reflection in the package API

In Alan Donovan and Brian Kernighan's "The Go programming language" book p333 (section 12.3 Display, a recursive value printer), it is mentioned that
Where possible, you should avoid exposing reflection in the API of a package. We'll define an unexported function display to do the real work of the recursion, and export Display, a simple wrapper around it that accepts an interface{} parameter.
func Display(name string, x interface{}) {
fmt.Printf("Display %s (%T):\n", name, x)
display(name, reflection.ValueOf(x))
And the display function prints different contents depending on the Kind of the input reflection value.
I have two questions
Why is it better to not expose the reflection in the package API?
Why is using an unexposed display function considered as not exposing reflection in the API? Don't we still call reflection.ValueOf() in Display?
I guess I don't know the definition of "exposing reflection in the package API". Does it just refer to the function arguments or both arguments and content? If it's the former case, then there seems no need to define display since the signature of Display is x interface{}. If it's the latter case, why is it better?
In the book's example
In the book's example, it is because the usage of reflection is an implementation detail. You should always try to hide the implementation details, so you may change the implementation at any time without breaking the "public" API of the package. If you export / add something to the API of your package, you have to carry that for the rest of your life (given you don't want to make backward-incompatible API changes, which is really bad in general).
In general
"interface{} says nothing" – Rob Pike. Given that, reflect.Value says even less. Unless you have a good reason (can't think of any outside of the reflect package itself), you shouldn't create public functions that expect reflect.Value as their arguments.
Even if you have a "general" function that must take a value of any type, interface{} is preferred as then at least the clients can pass what they have as-is, without having to wrap them in reflect.Value.

Endeca Assembler: Customize response header

I want to insert a new (key -> value) pair in response header from Endeca Assembler. Is it possible to do this?
Thanks
First of all, I want to clarify some things because the terminology about Assembler can get a little confusing. I'm not sure how you have designed your program, but just keep in mind that Assembler is just a Java API, so it's kind of unclear to say something like "response header from Endeca Assembler". That statement seems to imply that Assembler is a webservice, but it isn't. In my experience, people commonly mistakenly refer to the discover-data (Discover service) example app as "Assembler" or "Assembler Service", but it really isn't a general-purpose webservice; it's designed as a reference application to be used specifically with the Discover dataset (But people still use discover-data as a starting point for building production-facing applications). So, bear in mind that I'm not exactly sure what you are referring to.
Anyway, somewhere in your code, you should have a call of something like "contentItem.assemble()", which runs your cartridge handlers on that content item and returns an object of type ContentItem. In the Discover webapp, it then serializes this content item to JSON or XML or renders a JSP page (depending on the request parameters). I assume your application does something similar.
It's a simple matter of adding properties to ContentItem, because ContentItem implements map. So, you can do something like this:
ContentItem responseContentItem = contentItem.assemble();
responseContentItem.put("myKey","myValue");
...continue by serializing responseContentItem or whatever you want to do with it
Do like this:
responseContentItem.put("key", "value");
as the resposne from Endeca Assembler is simply a Map.

keep around a piece of context built during compile-time for later use in runtime?

I'm aware this might be a broad question (there's no specific code for you to look at), but I'm hoping I'd get some insights as to what to do, or how to approach the problem.
To keep things simple, suppose the compiler that I'm writing performs these three steps:
parse (and bind all variables)
typecheck
codegen
Also the language that I'm building the compiler for wants to support late-analysis/late-binding (ie., it has a function that takes a String, which is to be compiled and executed as a piece of source-code during runtime).
Now during parse-phase, I have a piece of context that I need to keep around till run-time for the sole benefit of the aforementioned function (because it needs to parse and typecheck its argument in that context).
So the question, how should I do this? What do other compilers do?
Should I just serialise the context object to disk (codegen for it) and resurrect it during run-time or something?
Thanks
Yes, you'll need to emit the type information (or other context, you weren't very specific) in your object/executable files, so that your eval can read it at runtime. You might look at Java's .class file format for inspiration; Java doesn't have eval as such, but you can dynamically spin new bytecode at runtime that must be linked in a type-safe manner. David Conrad's comment is spot-on: this information can also be used to implement reflection, if your language has such a feature.
That's as much as I can help you without more specifics.

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.