Match class that implements inteface and method with specified return type - javaagents

I wonder if it is possible to write byte-buddy java-agent which will find in project classes that implement specified interface, and match, in those classes, methods that return also specified type ?

Yes, this is possible. You can apply the agent builder for this:
new AgentBuilder.Default()
.type(ElementMatchers.isSubTypeOf(YourInterface.class))
.transform((builder, type, cl, module) ->
builder.method(returns(YourReturnType.class)).intercept( ... )
).installOn(inst);

Related

Different ways to define a function in Kotlin

I'm new at Kotlin, migrating from Java. One thing I think is a little bit confusing is the fact we may declare a function using different ways. Bellow are at least 3 ways to accomplish that:
package me.bruno.santana
class MyClass {
fun square(number: Int) = number * number
fun square2(number: Int): Int{
return number * number
}
}
fun MyClass.square3(number: Int) = number * number
fun main(){
val obj = MyClass()
println(obj.square(3))
println(obj.square2(3))
println(obj.square3(3))
}
What is the difference between this 3 ways in practical terms? I know the last one is related to extension funcion concept, but I don't know what it differs from the conventional way in practical terms.
Another thing is weird for me is the assignment in the function definition(using equals sign to associate the function's body to the function's signature). Is it in any way different from the convetional way using curly braces as in Java?
Thank you.
1. This is single expression function:
When a function returns a single expression, the curly braces can be omitted and the body is specified after a = symbol
Explicitly declaring the return type is optional when this can be inferred by the compiler:
fun square(number: Int) = number * number
2. This is normal function
That can have single-line or multi-lines and required return type (but Unit is optional):
fun square2(number: Int): Int {
return number * number
}
3. This is Extension functions:
Kotlin provides the ability to extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator.
Extensions are resolved statically: Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type
Often used to write utility functions and enhance readability via dot-notation.
If an extension is declared outside its receiver type, such an extension cannot access the receiver's private members.
fun MyClass.square3(number: Int) = number * number
To add something about extension functions: there are four common reasons to use them that I can think of.
You don't control the source code of the class you're adding the function to.
You want to add functions only to specifically typed instances of a class. For example, you could write a function for your Foo<T: Animal> class that is only available on instances that are a Foo<Pet>.
You want to add something like a final function to an interface. This is used frequently in the standard library. If you define a function inside an interface, its behavior is unpredictable because interface functions cannot be final. By declaring it outside the interface as an extension, it can be hidden (by writing a different extension function with the same signature), but it cannot be overridden. Hiding it still requires the user to import the other version of the function, so it must be done explicitly.
You want to confine the scope of the added function. Maybe the function only really makes sense in a certain context, so you don't want it to clutter the IDE auto-complete everywhere. Or maybe it uses a property of a certain class, so it must be defined within that class.
When you're just composing one of your own typical classes, you won't frequently need to use an extension function.

Limit argument type to package, possible?

In AS3, the below method accepts a parameter of any type:
public function myFunc(data:*) :void
Is it possible to limit the type to a specific package? Something like this maybe:
public function myFunc(data:(my.package:*)) //Accepts any type from my.package
It is possible, but will only have type control at runtime.
import flash.utils.getQualifiedClassName;
public function myFunc(data:*):void {
if (data is Object) {
var fqcn:String=getQualifiedClassName(data);
if (fqcn.slice(0,10)!='my.package') return; // otherwise work
// work here
} // simple types process if needed
}
This sounds like a design issue. One way to make this work during compile is if the parameter type is a custom class:
public function myFunc(data:MyCustomClass):void
Assuming that all the classes within my.package are varied, you could create a custom base class that extends Object and have all of your classes within my.package extend from this base class. Of course, If, however, the inheritance of your my.package classes is less broad you wouldn't need to reach so far. For example, you should only extend from DisplayObject if all the classes within my.package are of that type.
There may also be a way to accomplish what you want using namespaces, but I'm unsure.

Actionscript 3 - passing custom class as parameter to custom class where parameter class not constructed

Hi and thanks in advance,
I have a custom class being constructed from my main class. In the custom class it has another custom class that is passed in as a parameter. I would like to strictly type the parameter variable but when I do, 'the type is not a compile type constant etc'.
This, I understand, is because the custom class used as a parameter has not yet been constructed.
It all works when I use the variable type ( * ) to type the parameter.
I suspect this is a design flaw, in that I am using an incorrect design pattern. It is actually hand-me-down code, having received a large project from someone else who is not entirely familiar with oop concepts and design patterns.
I have considered using a dummy constructor for the parametered class in my main class but the passed in class also takes a custom class (itself with a parametered constructor). I am considering using ... (rest) so that the custom classes' parameters are optional.
Is there any other way to control the order of construction of classes? Would the rest variables work?
Thanks
(edit)
in main.as within the constructor or another function
var parameter1:customclass2;
customclass1(parameter1);
in customclass1 constructor:
public function customclass1(parameter1:customclass2)
{
....
Flash complains that the compiled type cannot be found when I use the data type customclass 2 in the paramater. It does not complain when I use the variable data type * or leave out the data type (which then defaults to * anyway). I reason that this is because customclass2 has not yet been constructed and is therefore not available to the compiler.
Alternatively, I have not added the path of customclass2 to the compiler but I am fairly certain I have ruled this out.
There are over 10,000 lines of code and the whole thing works very well. I am rewriting simply to optimise for the compiler - strict data typing, error handling, etc. If I find a situation where inheritance etc is available as an option then I'll use it but it is already divided into classes (at least in the main part). It is simply for my own peace of mind and to maintain a policy of strict data typing so that compiler optimization works more efficiently.
thnx
I have not added the path of customclass2 to the compiler but I am fairly certain I have ruled this out.
So if you don't have the class written anywhere what can the compiler do ? It is going to choke of course. You either have to write the CustomClass class file or just use "thing:Object" or "thing:Asteriks". It's not going to complain when you use the "*" class type because it could be anything an array, string, a previously declared class. But when you specify something that doesn't exists it will just choke, regardless of the order the parameters are declared in.

How to return multiple classes as IQueryable<T>

Using Linq I would like to return an object that contains customers and invoices they have.
I understand returning a single type from a method:
public IQueryable<customers> GetCustomers()
{
return from c in customers
select c;
}
But I am having trouble figuring out multiple objects:
public IQueryable<???> GetCustomersWithInvoices()
{
return from c in customers
from inv in c.invoices
select new {c, ci} // or I may specify columns, but rather not.
}
I have a feeling I am approaching this the wrong way. The goal is to call these objects from a controller and pass them up to a view, either direct or using a formViewModel class.
In the second case you are creating an annonymous type which has method scope. To pass an annonymous type outside the method boundary you need to change the return type to object. This however defeats the purpose of the annonymous type (as you lose the strong typing it provides) , requiring reflection to get access to the properties and their values for the said type.
If you want to maintain this structure as your return type you should create a class or struct consisting of properties to hold the customer and invoice values.
You cannot return an anonymous type from a function, they are strictly "inline" classes. You will need to create a concrete type to hold your members if you want to encapsulate them in a function.
Using a view model, as you mentioned, would be a good place to put them.
Here is a scottgu article about anonymous types. From the conclusion of the article:
Anonymous types are a convenient
language feature that enable
developers to concisely define inline
CLR types within code, without having
to explicitly provide a formal class
declaration of the type. Although
they can be used in lots of scenarios,
there are particularly useful when
querying and transforming/shaping data
with LINQ.
There's some good discussion in the comment thread on that page.
If you really want to, you can do this, but it is rather awkward.
public IQueryable<T> GetCustomersWithInvoices(T exampleObject)
{
return from c in customers
from inv in c.invoices
select new {c, ci} // or I may specify columns, but rather not.
}
var exampleObject = new {
Customer c = new Customer(),
Invoice i = new Invoice()
};
var returnedObjectOfAnonymousType = GetCustomersWithInvoices(exampleObject);
In this way, you can take advantage of type inference to get your method to return an anonymous type. You have to use this ugly method of passing in an example object to get it to work. I don't really recommend that you do this, but I believe that this is the only way to do it.

Why do static Create methods exist?

I was wondering, why do static Create methods exist?
For instance, why use this code:
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(inputUri);
over this code:
System.Xml.XmlReader reader = new System.Xml.XmlReader(inputUri);
I cannot find the rationale for using one over the other, and can't find any relation between classes who use this construct over the other.
Can anyone shed some light on this?
XmlReader is an abstract class. You cannot instantiate it.
Providing a Create method is an instance of the factory pattern. Depending on the specified arguments a different implementation of XmlReader is chosen and returned. For example, there are validating and non-validating XmlReader implementations in the .NET framework.
A more general answer...
The reason people like these kinds of methods, known as "static factory methods", is because you can give them a name (as opposed to constructors). So if you need three different constructors, you can instead create static factory methods which have names relevant to their use.
Another reason is that a factory method doesn't really need to create new objects - it can return the same one over and over if need be.
Because it can actually create and object of derived type that you have no access to or return an abstract class (as dtb answered). This is factory method pattern.
A constructor can only be used to create instances of one specific class, while a static Create method can create an instance of different classes depending on the input.
In the case of the XmlReader class the Create method will return an XmlDictionaryReader, XmlTextReader, XmlValidatingReader or XmlNodeReader, depending on which overload you use and what parameters you send to it.
This pattern allows the XmlReader class to provide you with instances of derived classes tailored to the parameters you passed to Create. Note in particular the overloads that accept an XmlReaderSettings object. A different XmlReader subclass can be returned to you depending on your settings.
A better example is WebRequest.Create(url). Depending on the URL you pass, you may receive an HttpWebRequest, an FtpWebRequest, etc.
Because you don't have to commit to the exact class of object you get. Constructors can only construct objects from exactly one class.
Because you can give the method a meaningful name, e.g. BigInt.probablePrime(). Constructors can only have the same name as the class.
Because you can have more than one factory method for the same parameter type combination, e.g. Point.fromPolarCoords(int, int) and Point.fromCartesianCoords(int, int), but there can be only one constructor Point(int, int).
(A much more detailed answer is given in Bloch's 'Effective Java'.)
Sometimes they exist as a form of self-documentation. I have a db access component that I can instantiate either with a connection string or the name of the connection in the config file. Both of these methods take strings as a parameter so they cannot be differentiated by arguments alone. So I created a FromConnectionString(string) factory method and a FromConnectionName(string) factory method. This nuance would entirely be lost by a new Foo(bool, string) line.
The idea is that this way they can change the implementation of XmlReader and not break any user code (e.g. they can change the actual type that is returned from the Create method).
I personally don't like this approach, because it creates an inverse relationship in the XmlReader class hierarchy. Maybe they thought that the Factory pattern is an overkill?
To encapsulate object creation.