mercredi 23 août 2017

Non-virtual method invocation using reflection

In Java, when working with java.lang.reflect.Method how can I invoke a function without it being a virtual call?

I.e. I want this code to print "good" instead of what it currently does, which is print "bad":

Foo.java:

public class Foo {
  public void doit() {
    System.out.println("good");
  }
}

Bar.java:

import java.lang.reflect.Method;

public class Bar extends Foo {
  public void doit() {
    System.out.println("bad");
  }

  public static void main(String[] args) throws Exception {
    Bar b = new Bar();
    /* Using Foo.class ought to do it right? */
    Method m = Foo.class.getDeclaredMethod("doit", new Class[]{});
    /* Surely if that didn't do it casting to Foo would? */
    m.invoke((Foo)b, new Object[]{});
  }
}

Nothing I do using reflection succeeds in printing "good".

My expectation was that using one or more of casting the first argument of invoke to Foo, and/or using Foo.class.getDeclaredMethod instead of Bar.class would be sufficient. Clearly I'm wrong about that, how can I get the desired behaviour still using reflection?





mardi 22 août 2017

C# Will reflection create multiple instance of a singleton in my assembly?

I am creating a c# based automated testing framework and have configuration files that link test case methods and class names to requirement IDs. The framework will create a TestPlan that is a list of multiple test cases that will executed one after another.

Since there are thousands of testcases (and more all the time) I want to call these classes and methods by reflection, but I am concerned that these methods will create singleton instances of supporting classes that will hang around after the method returns that won't be reused when the next test method is called by reflection.

My question is: will each call use the same static instance in the assembly? Or will each call create a new instance of the singleton? Without reflection in the mix it is a simple answer, but with it ... I am not certain.





How to find the instance in Java that called my static method so I can call methods on that instance? [duplicate]

This question already has an answer here:

I think what I need is AOP but I can't use AOP there. Need some neat workaround from a creative mind.

Problem is simple:

public class Hello {

    public void myMethod() {

        MyClass.myStaticMethod();

    }
}

public class MyClass {

    public static void myStaticMethod() {

        Object callerInstance = getTheInstanceWhoCalledMe();

        if (callerInstance instanceof Animal) {
            Animal a = (Animal) callerInstance;
            System.out.println(a.eat());
        }
    }

    public static Object getTheInstanceWhoCalledMe() {

        // ???????? Any creative genius out there?
    }
}





Recursively walk through nested structs

I want to build a method that takes a struct as an interface{} and returns true if any of the supplied struct's fields are nil.

Here's what I have at the moment:

// ContainsNil returns true if any fields within the supplied structure are nil.
//
// If the supplied object is not a struct, the method will panic.
// Nested structs are inspected recursively.
// Maps and slices are not inspected deeply. This may change.
func ContainsNil(obj interface{}) bool {
    if obj == nil {
        return true
    }
    s := reflect.Indirect(reflect.ValueOf(obj))
    for i := 0; i < s.NumField(); i++ {
        f := s.Type().Field(i)
        field := s.Field(i)
        if fieldIsExported(f) { // Exported-check must be evaluated first to avoid panic.
            if field.Kind() == reflect.Struct {
                if ContainsNil(field.Addr()) {
                    return true
                }
            } else {
                if field.IsNil() {
                    return true
                }
                if field.Interface() == nil {
                    return true
                }
            }
        }
    }
    return false
}

func fieldIsExported(field reflect.StructField) bool {
    log.Println(field.Name)
    return field.Name[0] >= 65 == true && field.Name[0] <= 90 == true
}

And a failing test:

func Test_ContainsNil_NilNestedValue_ReturnsTrue(t *testing.T) {
    someNestedStruct := &c.SomeNestedStruct{
        SomeStruct: c.SomeStruct{
            SomeString: nil,
        },
    }
    result := util.ContainsNil(someNestedStruct)
    assert.True(t, result)
}

The test code executes without panicking, but fails because the method returns false rather than true.

The issue I'm having is that I can't figure out how to properly pass the nested struct back into the recursive call to ContainsNil.

When recursive call is made for the nested structure, the fieldIsExported method returns false because it's not receiving the value that I would expect it to be receiving.

I expect fieldIsExported to receive "SomeStruct" on its first call, and receive "SomeString" on the second (recursive) call. The first call goes as expected, but on the second call, fieldIsExported receives "typ", when I would expect it to receive "SomeString".

I've done a bunch of research about using reflect on structs, but I haven't been able to get my head around this yet. Ideas?

References:





How do I get the name of the type currently held by an `any`?

Suppose I have either:

  1. A boost::any or
  2. An std::any (and I'm using C++17)

the type of which I don't know. Is it possible for me to print, or get as a string, the name of the type that's being held by the any?

Note: Even a mangled type name - the kind you get with typeid(TR).name() - would be sufficient I can take it from there using abi::__cxa_demangle.





Getting the JsonPropertyAttribute of a Property

I found a post with a great answer for a problem I have, but I can't seem to find a small detail I'm looking for.

public class myModel
{
   [JsonProperty(PropertyName = "id")]
   public long ID { get; set; }
   [JsonProperty(PropertyName = "some_string")]
   public string SomeString {get; set;} 
}

I need a method which returns the JsonProperty PropertyName of a specific property. Maybe something where I can pass the Type and the Property I need, and the method returns the value if found.

Here's the method I found which has me in the right direction (I believe) taken from here

using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
...

public static string GetFields(Type modelType)
{
    return string.Join(",",
        modelType.GetProperties()
                 .Select(p => p.GetCustomAttribute<JsonPropertyAttribute>()
                 .Where(jp => jp != null)
                 .Select(jp => jp.PropertyName));
}

The goal is to call a function like this (any modification is fine)

string field = GetField(myModel, myModel.ID);

Thanks!





Implementing a plugin architecture without split packages (Java Modules)

In a past question I asked how to design a system where:

  • A class contains one or more optional methods.
  • Optional methods are implemented by plugins that may or not may be present at compile-time.
  • If a user invokes a method whose associated plugin is not present at compile-time, they will get a compile-time error.

I provided one possible solution that works in Java 8.

Unfortunately, this solution depends on the use of split packages (two modules exporting the same package) which are disallowed by the Java 9 Module System.

How can this be implemented in Java 9?