Wrapping constructor call in the method to the static call using ASM bytecode manipulation - java-bytecode-asm

My query is related to bytecode manipulation using ASM.
I have one method as follows --
/*Original method code*/
String str ="abs";
// create object of SampleClass2 // constructor calling
SampleClass2 sample = new SampleClass2();
// call instance method
sample.PrintMe(str);
In the above method, I want to change the SampleClass2() constructor to one static method call which will return same SampleClass2 object after doing some logic. So after that my method will look something like this.
/*
* After bytecode manipulation*
*/
String str ="abs";
// get a constructor using static call
SampleClass2 sample = StaticClass.getSampleClass2Object();
sample.PrintMe(str);
Please tell me how can I achieve this using ASM bytecode manipulation. Do we need to change the existing bytecode stack for the same like DUP

The main problem is that the object is first created with a "new" instruction, followed by the call to the constructor. You'd have to replace both the "new" and the constructor call, which might be difficult to achieve. If you want to go along that road, make sure to check out Chapter 8 (Tree API -> Method Analysis) p 115 in the ASM documentation.
However, if that is enought, you could simply add a call to a static method to do some post instantiation logic, which is fairly simple. Just find the constructor call, and add a static invocation to a method afterwards which takes a SampleClass2 as parameter and returns a SampleClass2 (probably the same instance)

Related

Spock framework: what is the purpose of Spies vs. a using real object or Mock?

From the documentation:
A spy is always based on a real object. Hence you must provide a class type rather than an interface type, along with any constructor arguments for the type. If no constructor arguments are provided, the type’s default constructor will be used.
Method calls on a spy are automatically delegated to the real object. Likewise, values returned from the real object’s methods are passed back to the caller via the spy.
Also:
When stubbing a method on a spy, the real method no longer gets called:
subscriber.receive(_) >> "ok"
Instead of calling SubscriberImpl.receive, the receive method will now simply return "ok".
If a spy is just an interface layer between a real object and the caller, why not just use the real object? What does using a spy offer that using the real object or a Mock do not?
It seems to be in this void between a Mock and a real object to me.
Spies can be used in different scenarios. However, it is good if you can implement your tests without resorting to spies.
(Think twice before using this feature. It might be better to change the design of the code under specification.)
They can be used to verify that a method was called without mocking the method itself
You can stub out calls that you don't want to happen
You can use partial mocks to test the object itself
// this is now the object under specification, not a collaborator
def persister = Spy(MessagePersister) {
// stub a call on the same object
isPersistable(_) >> true
}
when:
persister.receive("msg")
then:
// demand a call on the same object
1 * persister.persist("msg")
Example and quote are from the docs # http://spockframework.org/spock/docs/1.1/all_in_one.html#Spies
In my practice I prefer to use a real objects as much as possible. In case when only one method is to be mocked I still use a real object but with overridden needed method:
MyDomainClass myRealObjectWithMockedMethod = new MyDomainClass() {
#Override
Object doSomething() {
return "hard coded or mocked result";
}
}
// test what you need
myRealObjectWithMockedMethod.action();
Note, this way works only of overridden method is not final. Otherwise Spy will help to define a behavior of this method.
A spy offers the possibility to use the original object but also mock out one method. For example you have a class where you want to test the implementation of the toString() method. But this calls an long running method which needs some external access like a database. In this case you use a spy and let your long running method return some test string and then use the toString from the original object.
Or like the spock example the method subscriber.receive maybe needs a server which sends out asynchronous messages. To write an test for subscriber not relying on the server or to handle asynchronous complexity you let the spy return ok and can easily test your methods which will rely on a server ok.

Mockito.when() not working

I am trying to mock a call to a protected method of one of my classes:
import com.couchbase.client.java.view.Stale; // an enum
import com.google.common.base.Optional;
public class MyClass {
public List<String> myList(Optional<Integer> arg1, Optional<Stale> arg2) {
...
}
}
The mock shall be accomplished in the following way:
// Providing types for any() does not change anything
Mockito.when(myClass.myList(Mockito.any(), Mockito.any()).thenReturn(new ArrayList());
Whenever the previous line is executed the actual myList() method is called with null values for arg1 and arg2. Why is the method called, at all? After all, I am trying to avoid any executing thereof...
As Brice mentioned, if your myList method is final, then Java skips virtual method dispatch and will call the original object (not your mock).
If you are spying on an actual class, it is expected behavior that when will call the actual object as part of the stub: after all, in the expression when(foo.bar()) Java doesn't know anything special about when and assumes that it cares about the return value) of foo.bar(), not the call itself. (I walk through the stubbing process in the "Implementation details" section of my answer here.)
This syntax is better for spies:
doReturn(new ArrayList()).when(myClass).myList(any(), any());
Because this different when method receives an object, Mockito can prepare the object to do nothing during the stubbing, which avoids any spurious calls to your myList method.
Although Jeff's answer did not show a workaround for my problem it pointed me into the right direction.
After changing the mocking behaviour to doReturn... I suddenly got an error message. This message told me that myClass is not a mock which makes sense since you can only mock (or stub?) methods of mocked or spied objects. So as Jeff's answer indicates and is explained in the documentation of mockito I created a partial mock of MyClass with
MyClass myClass = Mockito.spy(new MyClass());
With this partial mock Jeff's approach to method mocking suddenly worked (mine still does not and should therefore be avoided).
So: Thank you, Jeff!

Calling C++(cocos2dx) method from java(android) for my in-app billing

I'm trying to add in-app billing in my cocos2dx-android project. I am able to give a call to java function from c++ class via jni.
This is the way i give a call to my java function via jni.
JniMethodInfo t;
JniHelper::getStaticMethodInfo(t
, "com/test/project/Project"
, "BuyProduct"
, "(Ljava/lang/String;)V");
char buffer[20];
sprintf(buffer,"product1");
jstring StringArg1 = t.env->NewStringUTF(buffer);
t.env->CallStaticVoidMethod(t.classID, t.methodID, StringArg1);
The in-app billing is working fine, but now i have to give a call back to my c++ class to inform if the product purchase was successful or not.
I could return the result from the called method only by mentioning the specified return type, but the in-app process being a asynchronous process-goes through a lot of method calls, and my control is not returned back to the same method. So returning a value would not work.
So is there any other way of passing a value(in my case the result of in-app purchase) to my c++ class from java function???
check the cocos2dxHelper.cpp file to have a look how cocos2dx call c++ method.
basically there is a method in cocos2dxHelper.java which only have the definition but not the implementation, usually it looks like
public static native blahblah();
and there is a corresponding function in cpp file called
Java_org_cocos2dx_cocos2dxHelper_blahblah()
if you call the blahblah() in Java code with runOnUIThread(), the c++ function
Java_org_cocos2dx_cocos2dxHelper_blahblah()
will be called.
by the way, the c++ code need to be in something extern C { }

Pass a dynamic variable in a static parameter of a method in C# 4

This is what I am trying to do:
public void method(int myVal, string myOtherVal)
{
// doing something
}
dynamic myVar = new SomeDynamicObjectImplementer();
method(myVar.IntProperty, myVar.StringProperty);
Note that my properties are also DynamicObjects. My problem is that the TryConvert method is never called and that I get a runtime error saying the method signature is invalid.
The following is working great:
string strVar = myVar.StringProperty;
int intVar = myVar.IntProperty;
And I would like to avoid
method((int)myVar.IntProperty, (string)myVar.StringProperty);
Is it possible to override something in DynamicObject to allow this? (or something else)
Thank you
The problem is your assumption that it will try a dynamic implicit convert on arguments of an dynamic invocation to make a method call work, this is not true.
When your arguments aren't statically typed, it will use the runtime type to find the best matching method (if the runtime type matches the static rules for implicit conversion to the argument type this will work too), since your your IntProperty,StringProperty seem to be returning a DynamicObject rather than an Int and a String or something that could statically be converter implicitly, this lookup will fail.
If SomeDynamicObjectImplementer could actually return an Int for IntProperty and a String for StringProperty your method call for without casting would actually work. It's also probably a better dynamic typing practice if you data type is based on the actually type of data rather than usage using try convert. You could add actually implicit convert methods for every possible type that you could return to that returned DynamicObject type, but that could cause strange resolution issues to depending on how much you are overloading.
However, another option to keep your dynamic implementation the same is to mix a little controlled static typing in, you can use ImpromputInterface (in nuget) to put an interface on top of a dynamic object, if you do that then the TryConvert method would be called on your returned DynamicObjects.
public interface ISomeStaticInterface{
int IntProperty {get;}
string StringProperty {get;}
}
...
var myVar = new SomeDynamicObjectImplementer().ActLike<ISomeStaticInterface>();
method(myVar.IntProperty, myVar.StringProperty);
Instead of using myVar.IntProperty can't you just put them in variables first, like you already did, and then use then for your method?
so method(intVar , strVar); seems fine. At least more elegant than casting.
Of course, if you're already certain your object will have IntProperty and StringProperty, why not just make an actual object with those properties instead?
Why are you doing the cast?
method(myVar.IntProperty, myVar.StringProperty);
should compile.
If the two properties must be the types suggested by the names then they shouldn't be dynamic.

What is the difference between static and dynamic binding?

Binding times can be classified between two types: static and dynamic. What is the difference between static and dynamic binding?
Could you give a quick example of each to further illustrate it?
In the most general terms, static binding means that references are resolved at compile time.
Animal a = new Animal();
a.Roar(); // The compiler can resolve this method call statically.
Dynamic binding means that references are resolved at run time.
public void MakeSomeNoise(object a) {
// Things happen...
((Animal) a).Roar(); // You won't know if this works until runtime!
}
It depends when the binding happens: at compile time (static) or at runtime (dynamic). Static binding is used when you call a simple class method. When you start dealing with class hierarchies and virtual methods, compiler will start using so called VTABLEs. At that time the compiler doesn't know exactly what method to call and it has to wait until runtime to figure out the right method to be invoked (this is done through VTABLE). This is called dynamic binding.
See Wikipedia article on Virtual tables for more details and references.
I came accross this perfect answer of a quora user "Monis Yousuf". He explain this perfectly. I am putting it here for others.
Binding is mostly a concept in object oriented programming related to Polymorphism.
Firstly, understand what Polymorphism is. Books say that it means "one name and multiple forms". True, but too abstract. Let us take a real-life example. You go to a "Doctor", a doctor may be an eye-specialist, ENT specialist, Neuro-Surgeon, Homeopath etc.
Here, a "doctor" is a name and may have multiple types; each performing their own function. This is polymorphism in real life.
Function Overloading: This concept depicts Static Binding. Function overloading may be roughly defined as, two or more methods (functions) which have the same name but different signatures (including number of parameters, types of parameters, differt return types) are called overloaded methods (or functions).
Suppose you have to calculate area of a rectangle and circle. See below code:-
class CalculateArea {
private static final double PI = 3.14;
/*
Method to return area of a rectangle
Area of rectangle = length X width
*/
double Area(double length, double width) {
return (length * width);
}
/*
Method to return area of circle
Area of circle = π * r * r
*/
double Area(double radius) {
return PI * radius * radius;
}
}
In above code, there are two methods "Area" with different parameters. This scenario qualifies as function overloading.
Now, coming to the real question: How is this static binding?
When you call any of the above functions in your code, you have to specify the parameters you are passing. In this scenario, you will pass either:
Two parameters of type double [Which will call the first method, to
calculate are of a rectangle]
Single parameter of type double [Which will call the second method, to calculate area of a circle]
Since, at compile time the java compiler can figure out, WHICH function to call, it is compile-time (or STATIC) binding.
Function Overriding: Function overriding is a concept which is shown in inheritance. It may roughly be defined as: when there is a method present in a parent class and its subclass also has the same method with SAME signature, it is called function overriding. [There is more to it, but for the sake of simplicity, i have written this definition] It will be easier to understand with below piece of code.
class ParentClass {
int show() {
System.out.println("I am from parent class");
}
}
class ChildClass extends ParentClass{
int show() {
System.out.println("I am from child class");
}
}
class SomeOtherClass {
public static void main (String[] s) {
ParentClass obj = new ChildClass();
obj.show();
}
}
In above code, the method show() is being overridden as the same signature (and name) is present in both parent and child classes.
In the third class, SomeOtherClass, A reference variable (obj) of type ParentClass holds the object of ChildClass. Next, the method show() is called from the same reference variable (obj).
Again, the same question: How is this Dynamic Binding?
At compile time, the compiler checks that the Reference variable is of type ParentClass and checks if the method show() is present in this class. Once it checks this, the compilation is successful.
Now, when the programs RUNS, it sees that the object is of ChildClass and hence, it runs the show() method of the ChildClass. Since this decision is taken place at RUNTIME, it is called Dynamic Binding (or Run-time Polymorphism).
Link for original answer
Static Binding: is the process of resolving types, members and operations at compile-time.
For example:
Car car = new Car();
car.Drive();
In this example compiler does the binding by looking for a parameterless Drive method on car object. If did not find that method! search for methods taking optional parameters, and if did not found that method again search base class of Car for that method, and if did not found that method again searches for extension methods for Car type. If no match found you'll get the compilation error!
I this case the binding is done by the compiler, and the binding depends on statically knowing the type of object. This makes it static binding.
Dynamic Binding: dynamic binding defers binding (The process of resolving types, members and operations) from compile-time to runtime.
For example:
dynamic d = new Car();
d.Drive();
A dynamic type tells the compiler we expect the runtime type of d to have Drive method, but we can't prove it statically. Since the d is dynamic, compiler defers binding Drive to d until runtime.
Dynamic binding is useful for cases that at compile-time we know that a certain function, member of operation exists but the compiler didn't know! This commonly occurs when we are interoperating with dynamic programming languages, COM and reflection.
Binding done at compile time is static binding and binding done at run time is dynamic binding.In static binding data type of the pointer resolves which method is invoked.But in dynamic binding data type of the object resolves which method is invoked.
* Execution time:-* bindings of variables to its values,as well as the binding of variable to particular storage location at the time of execution is called execution time binding.
IT MAY BE OF TWO TYPES
on entry to a subprogram.
At arbitrary points during execution time.
COMPILE TIME BINDING :- (TRANSLATION TIME)
It consist of the following.
Binding chosen by programmer.
Binding chosen by the translator.
Binding chosen by the loader.

Resources