Calling delegate from (get, set )Properties c# - c#-4.0

I need help to use the below piece of code to call Method1. There are no compilation issues but while running the code Method1 is not invoked. I searched the net a lot but didn't find a solution.
public static class Test12
{
public static Test12.ByteDelegate PropertyValue { get; set; }
public delegate byte[] ByteDelegate(byte p1, byte[] p2);
}
The above class has to be used like this:
class Abc
{
internal void Stat()
{
Test12.Propertyvalue = Method1;
}
private byte[] Method1(byte p1, byte[] p2)
{
byte[] abc = ...;
return abc;
}
}
If I am creating an instance of the delegate in stat method and using it like:
Method1(param1,param2);
Then the Method1 in invoked, but if I use it like this:
Test12.PropertyValue = Method1(param1,param2);
compiler is throwing an error saying missing typecast. Can anybody please tell me how to invoke Method1 using Test12.PropertyValue = Method1;?

You receive an error message because when you try to assign the method to the delegate you are using the following line of code:
test12.propertyvalue = method1(param1, param2);
Which firstly calls the method1 and then what it returns it's trying to assign to the delegate, and the error message occurs saying that you can't assign a byte array to a delegate, as #Jon said in the comment. They are different types so you can't assign one to another, at least not without a cast or a conversion method.
In order to invoke the method1 from the delegate, after you do the assignation like this:
test12.propertyvalue = method1;
you can simply call the delegate, as it would be your method:
test12.propertyvalue(param1 , param2);

Related

Is there any way to mock field of Class

Here's my case, I have a class A which has one member field b. And I want to test and in unit test, I mocked A and also need to call method f() which will invoke b's f(). But the b variable in mocked A is null, so will throw NPE, and I have no get/set method for b, so is there any way to mock b ? THanks
public static class B{
public void f() {
}
}
public static class A {
B b;
public void f() {
b.f();
}
}
If you want to mock out the b property of A in a test, you've given the b property default (package-private) access, so as long as your test is in the same package you could replace the b property directly.
#Test
public void testB() {
A underTest = new A();
B mockedB = Mockito.mock(B.class);
underTest.b = mockedB;
underTest.f();
Mockito.verify(mockedB).f();
}
As an aside, I personally dislike using package-private access to mess around with member properties for tests, and instead would recommend a dependency injection framework like Guice or Spring DI for constructor injection.
However you've described that you've mocked out A, I'd have thought if this was the case the f() method of A would do nothing - you wouldn't get a null pointer exception as the call to the mock will replace the real b property and just be a void method that does nothing. Please can you provide more details if this is the case?

How to get `this' from a passed method

If one pass a method as a funarg, how one can tell if passed function is a method, and get `this' object of a method is?
class A {
public function f():Void{
trace("f");
}
}
class B {
static function withFunarg(f:Void->Void):Void{
//HERE
}
public static function main(){
var a = new A();
withFunarg(a.f);
}
}
You cannot and there is no way to retrieve this. But it seems to me like an anti-pattern trying to do that. If you want the method and the container you can define a typedef:
typedef F = {
f : Void -> Void
}
Now you have the method and the container.
Haxe doesn't offer a cross-platform way to do that and it is generally not recomended.
But if you ultimately need this feature, you can use some platform-specific ways.
For example on js the following will work(at least on current haxe dev version):
static function getThis(f:Dynamic):Dynamic{
return (f.scope && f.method) ? f.scope : null;
}
It will return the object if the function is a method and a null otherwise. Result on calling on non-function is unspecified.
If you want to get the implicit `this' argument of a method, you have to make it explicit, like this
static function withMethodFunarg(o:{}, f:{}->Void):Void{
//HERE you have both object and function on this object
trace(o);
f(o);
}
public static function main(){
var a = new A();
withMethodFunarg(a,function(a){a.f()});
}
Which is, actually, pretty straight-forward: function is a function, no implicits, method caller is a method caller.

Regarding String functionality

I was developing the below class..
public class Test1
{
public void method(Object o)
{
System.out.println("Object Verion");
}
public void method(String s)
{
System.out.println("String Version");
}
public static void main(String args[])
{
Test1 question = new Test1();
//question.method(question);
question.method(null);
}
}
Now upon executing it invokes string version as output So please advise here string is treated as null and what should we pass to invoke the object version.Thanks in advance
All other things being equal, the most-specific method will be called. From the JLS:
15.12.2.5. Choosing the Most Specific Method
If more than one member method is both accessible and applicable to a
method invocation, it is necessary to choose one to provide the
descriptor for the run-time method dispatch. The Java programming
language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than
another if any invocation handled by the first method could be passed
on to the other one without a compile-time type error.
question.method(null) could mean either the String or Object overload, but since String is more specific (narrower) than Object, the String overload is the method that is called.

Using FieldInfo.SetValue with a DynamicObject as argument 2

I ran into a problem today when trying to set a field using FieldInfo.SetValue() passing a DynamicObject as the second argument. In my case, the field is a Guid and the DynamicObject should be able to convert itself to a one (using TryConvert) but it fails with an ArgumentException.
Some code that shows the problem:
// Simple impl of a DynamicObject to prove point
public class MyDynamicObj : DynamicObject
{
public override bool TryConvert(ConvertBinder binder, out object result)
{
result = null;
// Support converting this to a Guid
if (binder.Type == typeof(Guid))
{
result = Guid.NewGuid();
return true;
}
return false;
}
}
public class Test
{
public Guid MyField;
}
class Program
{
static void Main(string[] args)
{
dynamic myObj = new MyDynamicObj();
// This conversion works just fine
Guid guid = myObj;
var test = new Test();
var testField = typeof(Test).GetField("MyField");
// This, however, fails with:
// System.ArgumentException
// Object of type 'ConsoleApplication1.MyDynamicObj' cannot be converted to type 'System.Guid'.
testField.SetValue(test, myObj);
}
}
I'm not very familiar with the whole dynamicness of C# 4, but this felt to me like something that should work.. What am I doing wrong? Is there another way of doing this?
No, this shouldn't work - because the dynamic portion ends where your code ends. The compiler is calling a method with a signature of
void SetValue(Object obj, Object value)
That method call is dynamic, but it's just going to end up passing in a reference to the instance of MyDynamicObj. The call is resolved at execution time, but nothing in SetValue knows anything about the dynamic nature of the object whose reference you're passing in.
Basically you need to perform the dynamic part (the conversion in this case) in your code - the bit that involves the C# 4 compiler doing all its tricks. You've got to perform that conversion, and then you can call SetField.
To put it another way - it's a bit like calling SetField with a field of type XName, but passing in a string. Yes, there's a conversion from string to XName, but it's not SetField's job to work that out. That's the compiler's job.
Now, you can get this to work by making the compiler do some of the work, but you still need to do some with reflection:
static void Main(string[] args)
{
dynamic myObj = new MyDynamicObj();
var test = new Test();
var testField = typeof(Test).GetField("MyField");
var method = typeof(Program)
.GetMethod("Convert", BindingFlags.Static | BindingFlags.NonPublic);
method = method.MakeGenericMethod(testField.FieldType);
object converted = method.Invoke(null, new object[] {myObj});
testField.SetValue(test, converted);
}
static T Convert<T>(dynamic input)
{
return input;
}
You need an explicit cast to invoke the TryConvert:
testField.SetValue(test, (Guid)myObj);
Not sure if this is what you need though. Maybe there's some way to reflectively say ((DynamicObject)myObj).TryConvert(/*reflected destination type here*/, result)
Other attempts that failed, some of them require things like a certain interface be implemented, so they basically don't make use of TryConvert but maybe an alternative way to accomplish what you want:
Type secondType = testField.FieldType;
TypeConverter tc = TypeDescriptor.GetConverter(typeof(MyDynamicObj));
object secondObject = tc.ConvertTo(myObj,typeof( Guid));
//var secondObject = Convert.ChangeType(myObj, secondType);//Activator.CreateInstance(secondType);
//secondObject = myObj;
testField.SetValue(test, secondObject);

how to pass java class instance as a parameter to JNI method?

I'd like to pass java class object to JNI method,
And I want to call few methods in JNI method like below.
Is there anyone who have some example like below?
class JavaClassParameter{
void javaMethodTobeCalledInJNI(){
...java source...
}
}
class MainJavaClass{
void somemethod(){
JavaClassParameter object = new JavaClassParameter();
JNIMethod(object);
}
native void JNIMethod(JavaClassParameter object);
}
// C++ code
void JNIMethod(object){
object->javaMethodTobeCalledInJNI();
}
Your method declaration:
class MainJavaClass {
native void JNIMethod(JavaClassParameter object);
}
means javah should generate a forward declaration like the following:
JNIEXPORT void JNICALL Java_MainJavaClass_JNIMethod(JNIEnv* env, jobject mainJavaClass);
In the implementation of that, you have a few things to do:
Find JavaClassParameter
Use FindClass, which takes a string name:
jclass cls = env->FindClass("JavaClassParameter");
Find javaMethodTobeCalledInJNI()
Use GetMethodID, which takes the class to check, the string name of the method, and its signature. Since this is a void function with no arguments, its signature is just ()V:
jmethodID method = env->GetMethodID(cls, "javaMethodTobeCalledInJNI", "()V");
Call javaMethodTobeCalledInJNI()
Use CallVoidMethod, which takes the object instance, the method ID, and any arguments (none in this case):
env->CallVoidMethod(mainJavaClass, method);
You should check for NULL results after each step; if you get a NULL back from one JNI function and pass it to another, you'll usually crash the JVM

Resources