bytecode tools: add method interceptor to classes (not proxy) - javassist

Javassist proxyFactory can create proxy at runtime with method interceptor. But how to add method interceptor to a class statically by modifying the class file?
For example, class Foo has 100 methods, before calling any method on an instance of Foo, need to check if the Foo instance is initialized.
public class Foo {
public void methodA() {
...
}
public void methodB() {
...
}
public void methodC() {
...
}
....
}
How to modify the class file to add such method interceptor? One way is to add code at the beginning of each method. Is there a better way?
How about other bytecode tools such as cglib, ....?

There are two options with ByteBuddy to achive this:
use redefine/rebase feature - You can check the details on ByteBuddy tutorial under 'type redefinition'/'type rebasing' tags. Limitation here is that this kind of transformation needs to be done before a target class is loaded.
Java Agent - agents run before class is loaded so they are allowed to modify existing classes. ByteBuddy comes with nice AgentBuilder (tutorial - 'Creating Java agents'). There is also posiblity to install special ByteBuddy agent at runtime (example from mentioned tutorial).
class Foo {
String m() { return "foo"; }
}
class Bar {
String m() { return "bar"; }
}
ByteBuddyAgent.install();
Foo foo = new Foo();
new ByteBuddy()
.redefine(Bar.class)
.name(Foo.class.getName())
.make()
.load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
assertThat(foo.m(), is("bar"));

Related

Make two factories return the same object that implements both interfaces

(I use C# in my examples, but this question is not specifically about C#.)
We have factories to create objects for multiple interfaces, one factory per interface.
Say we have a PrintingFactory to create an object implementing IPrinting and a ScanningFactory for IScanning. We have concrete printers implementing IPrinting and concrete scanners implementing IScanning and the factories decide which implementation is chosen.
In ScanningFactory I have:
public static IScanning Build()
{
...
return new CanonXYZ2000();
}
I have similar code in PrintingFactory, and in main I have:
scanner = ScanningFactory.Build();
printer = PrintingFactory.Build();
Now, what happens if I want to instantiate one object that implements both interfaces?
public class CanonXYZ2001MultiPurpose: IPrinting, IScanning {...}
I would like both factories to return the same object. How do I do this properly?
If i understand you correctly you are asking if CanonXYZ2001MultiPurpose can be created by both ScanningFactory and PrintingFactory ?
In this case both factories can return instances of CanonXYZ2001MultiPurpose with no issues, since this class implements both interfaces:
Scanning factory code:
public static IScanning Build()
{
...
return new CanonXYZ2001MultiPurpose ();
}
Printing factory code:
public static IPrinting Build()
{
...
return new CanonXYZ2001MultiPurpose ();
}
Both variables now hold instance of CanonXYZ2001MultiPurpose:
var scanner = ScanningFactory.Build();
var printer = PrintingFactory.Build();

redefine static methods with ByteBuddy

Can homebody help me please to give me a hint how to redefine static methods using byte-buddy 1.6.9 ?
I have tried this :
public class Source {
public static String hello(String name) {return null;}
}
public class Target {
public static String hello(String name) {
return "Hello" + name+ "!";
}
}
String helloWorld = new ByteBuddy()
.redefine(Source.class)
.method(named("hello"))
.intercept(MethodDelegation.to(Target.class))
.make()
.load(getClass().getClassLoader())
.getLoaded()
.newInstance()
.hello("World");
I got following Exception :
Exception in thread "main" java.lang.IllegalStateException: Cannot inject already loaded type: class delegation.Source
Thanks
Classes can only be loaded once by each class loader. In order to replace a method, you would need to use a Java agent to hook into the JVM's HotSwap feature.
Byte Buddy provides a class loading strategy that uses such an agent, use:
.load(Source.class.getClassLoader(),
ClassReloadingStrategy.fromInstalledAgent());
This does however require you to install a Java agent. On a JDK, you can do so programmatically, by ByteBuddyAgent.install() (included in the byte-buddy-agent artifact). On a JVM, you have to specify the agent on the command line.

Singleton subclass

I have an abstract base class and an implementation class like:
public abstract class Base
{
public Base getInstance( Class<? extends Base> clazz )
{
//expected to return a singleton instance of clazz's class
}
public abstract absMeth();
}
public A extends Base
{
//expected to be a singleton
}
In this example I can make A to be a singleton and even write getInstance in Base to return a singleton object of A for every call, doing this way:
public abstract class Base
{
public Base getInstance( Class<? extends Base> clazz )
{
try
{
return clazz.getDeclaredMethod("getInstance").invoke(null,null);
}
}
public abstract void absMeth();
}
public A extends Base
{
private static A inst;
private A(){}
public static A getInstance( )
{
if( inst!= null)
inst = new A();
return inst;
}
public void absMeth(){
//...
}
}
But my concern is how do I ensure that if somebody writes another class class B extends Base it should also be a singleton and it necessarily implements a static method called getInstance?
In other words I need to enforce this as a specification for all classes extending with the Base class.
You cannot trust classes that extend you to create a single instance of themselves1: even if you could somehow ensure that they all implement getInstance, there is no way to tell that inside that method they check inst before constructing a new instance of themselves.
Stay in control of the process: create a Map<Class,Base>, and instantiate the class passed in through reflection2. Now your code can decide whether to create an instance or not, without relying on the getInstance of a subclass.
1 A popular saying goes, "If you want a job done right, do it yourself."
2 Here is a link describing a solution based on setAccessible(true)
Singleton is a design pattern, not a language feature. It is pretty much impossible to somehow enforce it on the inheritance tree through syntax.
It certainly is possible to require all subclasses to implement a method by declaring it abstract but there is no way to control implementation details. Singleton is all about implementation details.
But why is this a concern at all? Do not make your app dependant on internal details of someone else's code. It is Bad Design™ and having this issue is a sure sign of it. Code against a well-defined interface and avoid relying on internal details.

Using Ninject to bind an interface to multiple implementations unknown at compile time

I just recently started using Ninject (v2.2.0.0) in my ASP.NET MVC 3 application. So far I'm thrilled with it, but I ran into a situation I can't seem to figure out.
What I'd like to do is bind an interface to concrete implementations and have Ninject be able to inject the concrete implementation into a constructor using a factory (that will also be registered with Ninject). The problem is that I'd like my constructor to reference the concrete type, not the interface.
Here is an example:
public class SomeInterfaceFactory<T> where T: ISomeInterface, new()
{
public T CreateInstance()
{
// Activation and initialization logic here
}
}
public interface ISomeInterface
{
}
public class SomeImplementationA : ISomeInterface
{
public string PropertyA { get; set; }
}
public class SomeImplementationB : ISomeInterface
{
public string PropertyB { get; set; }
}
public class Foo
{
public Foo(SomeImplementationA implA)
{
Console.WriteLine(implA.PropertyA);
}
}
public class Bar
{
public Bar(SomeImplementationB implB)
{
Console.WriteLine(implB.PropertyB);
}
}
Elsewhere, I'd like to bind using just the interface:
kernel.Bind<Foo>().ToSelf();
kernel.Bind<Bar>().ToSelf();
kernel.Bind(typeof(SomeInterfaceFactory<>)).ToSelf();
kernel.Bind<ISomeInterface>().To ...something that will create and use the factory
Then, when requesting an instance of Foo from Ninject, it would see that one of the constructors parameters implements a bound interface, fetch the factory, and instantiate the correct concrete type (SomeImplementationA) and pass it to Foo's constructor.
The reason behind this is that I will have many implementations of ISomeInterface and I'd prefer to avoid having to bind each one individually. Some of these implementations may not be known at compile time.
I tried using:
kernel.Bind<ISomeInterface>().ToProvider<SomeProvider>();
The provider retrieves the factory based on the requested service type then calls its CreateInstance method, returning the concrete type:
public class SomeProvider : Provider<ISomeInterface>
{
protected override ISomeInterface CreateInstance(IContext context)
{
var factory = context.Kernel.Get(typeof(SomeInterfaceFactory<>)
.MakeGenericType(context.Request.Service));
var method = factory.GetType().GetMethod("CreateInstance");
return (ISomeInterface)method.Invoke();
}
}
However, my provider was never invoked.
I'm curious if Ninject can support this situation and, if so, how I might go about solving this problem.
I hope this is enough information to explain my situation. Please let me know if I should elaborate further.
Thank you!
It seems you have misunderstood how ninject works. In case you create Foo it sees that it requires a SomeImplementationA and will try to create an instance for it. So you need to define a binding for SomeImplementationA and not for ISomeInterface.
Also most likely your implementation breaks the Dependency Inversion Princple because you rely upon concrete instances instead of abstractions.
The solution to register all similar types at once (and the prefered way to configure IoC containers) is to use configuration by conventions. See the Ninject.Extensions.Conventions extenstion.

Inheriting ConstructorArguments in Ninject

I'm trying to find a method of passing a constructor argument to the constructors of child classes.
These objects are immutable so I'd prefer to use constructor arguments.
The issue I have encountered is that ConstructorArgument does not inherit to child instantiations and the following statements are not interchangeable:
_parsingProcessor = _kernel.Get<IParsingProcessor>(new ConstructorArgument("dataFilePath", dataFilePath);
and
_parsingProcessor = _kernel.Get<IParsingProcessor>(new Parameter("dataFilePath", dataFilePath, true);
So, how can get an inheritable ConstructorArgument and when does it makes sense, if ever, to new the Parameter class?
Yes, you can do this, but it's probably not what you really want. If the container is not actually responsible for instantiating its own dependencies, then its dependencies probably shouldn't be sharing its constructor arguments - it just doesn't make sense.
I'm pretty sure I know what you're trying to do, and the recommended approach is to create a unique binding specifically for your one container, and use the WhenInjectedInto conditional binding syntax, as in the example below:
public class Hello : IHello
{
private readonly string name;
public Hello(string name)
{
this.name = name;
}
public void SayHello()
{
Console.WriteLine("Hello, {0}!", name);
}
}
This is the class that takes a constructor argument which we want to modify, depending on who is asking for an IHello. Let's say it's this boring container class:
public class MyApp : IApp
{
private readonly IHello hello;
public MyApp(IHello hello)
{
this.hello = hello;
}
public virtual void Run()
{
hello.SayHello();
Console.ReadLine();
}
}
Now, here's how you do up the bindings:
public class MainModule : NinjectModule
{
public override void Load()
{
Bind<IApp>().To<MyApp>();
Bind<IHello>().To<Hello>()
.WithConstructorArgument("name", "Jim");
Bind<IHello>().To<Hello>()
.WhenInjectedInto<MyApp>()
.WithConstructorArgument("name", "Bob");
}
}
Basically all this binding is doing is saying the name should be "Jim" unless it's being requested by Hello, which in this case it is, so instead it will get the name "Bob".
If you are absolutely certain that you truly want cascading behaviour and understand that this is very dangerous and brittle, you can cheat using a method binding. Assuming that we've now added a name argument to the MyApp class for some unspecified purpose, the binding would be:
Bind<IHello>().ToMethod(ctx =>
ctx.Kernel.Get<Hello>(ctx.Request.ParentContext.Parameters
.OfType<ConstructorArgument>()
.Where(c => c.Name == "name")
.First()));
Please, please, make sure you are positive that this is what you want before doing it. It looks easy but it is also very likely to break during a simple refactoring, and 95% of the "customized dependency" scenarios I've seen can be addressed using the WhenInjectedInto binding instead.