samedi 31 juillet 2021

Get function closure without reflection

I am using php < 5.4.0

Get closure of function/method with reflection is simple, but how to get function/method closure without reflection, and is it possible?





vendredi 30 juillet 2021

How to use class name dynamically using its name in c#?

I want to insert object to my repository but not explicitly.

 _repository<Car>().Add(carObject); // explicit

instead of this, I want to push the object to the corresponding class name at the run time. I can create the object in run time but can't set the class name in __repository<???>().Add(object) here.
For example: I've a string name "Car" [it might be other class name like "Person" ], then how can I do the same thing using the given code?
If you need more information I can provide. Thanks.





C# Reflection - Getting all types that implement interface and applying them by class type?

I am getting all instances of classes that implement an interface but I need to pass that class type into a Type field and I keep getting "x is a variable but used like a type". How can I get these classes as their type?

Here is my code that pulls in what implements the Interface ICacheData:

private IEnumerable<Type> GetCachables()
{
    var type = typeof(ICacheData);
    var types = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(s => s.GetTypes())
        .Where(p => type.IsAssignableFrom(p));
    return types;
}

But when trying to apply them into this call, I get an error.

var cacheables = GetCachables();
foreach(var cacheable in cacheables)
{
       var cacheItems = LoadAllFromCacheAsync<cacheable>(db, "");
}

LoadAllFromCacheAsync is defined as:

protected static async Task<List<T>> LoadAllFromCacheAsync<T>(DbEntities db, string eagerLoadProps = "") where T : class, ICacheData




How to get a value from a Non-Public member in C#

I am trying to access the name of a Sprint of a Jira Issue. The custom field sprint is null but the value I need exists in the Non-Public members. I am interested in accessing the name of the Sprint. I have tried to use Reflection, but I am probably doing something wrong because I always get null.

enter image description here

Can someone please help me? Thank you a lot!





Creating instances of generic base class

I am working with the Dapper.FluentMap library, and trying to set up auto-registration of my mapping classes. To do that, I need to call FluentMapConfiguration.AddMap<T>(EntityBase<T>) for each of the mapping classes.

I can do it like this:

public class TypeAMap : EntityMap<TypeA> {}
public class TypeBMap : EntityMap<TypeB> {}
public class TypeCMap : EntityMap<TypeC> {}

public void Register(FluentMapConfiguration configuration)
{
  configuration.AddMap(new TypeAMap());
  configuration.AddMap(new TypeBMap());
  configuration.AddMap(new TypeCMap());
  // I have a hundred of these, you can see where I'm going...
}

Obviously a problem in the making when you forget to register a map and wonder why your data isn't loading properly. So on to some reflection to auto-register:

public void Register(FluentMapConfiguration configuration)
{
  var maps = GetType().Assembly.GetExportedTypes().Where(t =>
      !t.IsAbstract &&
      !t.IsInterface &&
      t.BaseType is { IsGenericType: true } &&
      t.BaseType.GetGenericTypeDefinition() == typeof(EntityMap<>)
    ).ToArray();

    foreach (var map in maps)
    {
      var baseType = typeof(EntityMap<>);
      var typeArguments = map.BaseType.GetGenericArguments();
      var genericType = baseType.MakeGenericType(typeArguments);
      var instance = Activator.CreateInstance(genericType);

      configuration.AddMap((dynamic) instance);
    }
}

but when it gets to the call to Activator.CreateInstance, it fails, with a MissingMethodException, Cannot create abstract class. It looks like it's trying to create an instance of EntityBase<TypeA> rather than TypeAMap, and since EntityBase<T> is an abstract class, I'm getting the error. So how can I construct my instances correctly?





jeudi 29 juillet 2021

check if unknown interface{} is empty

Hello I would like to know how I would be able to validate in Go if an interface{} is empty. I tried reflect.TypeOf(v) == nil, but it always returns false.

    var h  Bar
    var t  Foo
    pointers := make([]interface{}, 0)
    pointers = append(pointers, &h)
    pointers = append(pointers, &t)

func test(byteValue []byte, data []interface{}) {
    for _, v := range  data {
        fmt.Println(reflect.TypeOf(v) == nil)
        if err := lib.Unmarshal(byteValue, v); err == nil {
            fmt.Println(err)
        }
    }
}




How to convert map[interface{}]interface{} to map[string]string with reflection

I have a struct

type ClientSubscriptions struct {
    ID         int64
    Service    string
    Identifier string
    EventType  string
    DateBegin  *time.Time
    DateEnd    *time.Time
    Extra      map[string]string
}

and i have an origin source which send me some data. I have no problems with parsing such types as int64, string and time. But i can't convert json object Extra to my struct

func parseSubscription(data []interface{}) (*ClientSubscriptions, error) {
    if len(data) == 0 {
        return nil, nil
    }

    res := ClientSubscriptions{}
    values := reflect.ValueOf(&res).Elem()
    controlTupleSize := values.NumField()

    if len(data) < controlTupleSize {
        return nil,
            fmt.Errorf("unexpected control tuple size %d, want %d", len(data), controlTupleSize)
    }

    for i, v := range data {
        value := values.Field(i)
        switch value.Interface().(type) {
        case int64:
            val, err := utils.ParseToInt64(v)
            if err != nil {
                return nil, err
            }
            value.SetInt(val)
        case *time.Time:
            val := v.(uint64)
            date := time.Unix(int64(val), 0)
            value.Set(reflect.ValueOf(&date))
        case string:
            val := v.(string)
            value.SetString(val)
        case interface{}:
            val := v.(map[string]interface{})
            if len(val) > 0 {
                for key, info := range val {
                    strKey := fmt.Sprintf("%v", key)
                    strValue := fmt.Sprintf("%v", info)
                    value.SetMapIndex(reflect.ValueOf(strKey), reflect.ValueOf(strValue))
                }
            }
        }

    }

    return &res, nil
}

panic: assignment to entry in nil map





Type trait to determine a data member's access specifier from a pointer-to-member to that member

I'm looking for a type trait that will allow me to find out if a pointer-to-member points to a public data member or not.

Example :

template<auto ptr>
struct is_public_member_ptr 
{
    // Possible?
};

class foo 
{
public:
    int i;
private:
    int j;

    static_assert(is_public_member_ptr<&foo::i>::value == true);
    static_assert(is_public_member_ptr<&foo::j>::value == false);
};

At first I considered using SFINAE to try and dereference the pointer-to-member and see if it worked, expecting substitution to fail for pointers to private members. Obviously that didn't work, you could only check if you are able to get the pointer-to-member in the first place. Once you have it, dereferencing will always succeed, even for private members.

This leads me to believe that there is no way to check the access specifier strictly from a pointer-to-member. That information isn't encoded into the pointer-to-member. But, it is possible to recover the original class to which the pointed member is a member of. So maybe there is some trick I missed.

Is this type trait achievable?

An ideal solution would be compatible with C++14, but solutions for any C++ version are fine too.





Java Reflection: create a constructor for an abstract class

If I have this class that I cannot modify...

public abstract class AClass {
    Object value;
    public AClass(Object value) { this.value = value; }
}

Then how would I create an instance of it with reflection?
This...

Class<?> clazz = // some class
Constructor</*someClass*/> constructor = AClass.class.getConstructor(clazz);
Object key = clazz.getConstructor(Object.class).newInstance(/*something*/);
/*someClassResult */ result = constructor.newInstance(key);

throws an InstantiationException at the last line.





How to filter the reflection for a field, after accessing it (with reflection)?

I was trying to make a system, where a class has a super-secret field (intero) and only the class itself and ANOTHER CLASS can access it. Then, there is a third class which i want to not have the permission to access that field.

The problem is - in java, you can use Reflections.registerFieldsToFilter() only before a field is accessed. If someone accesses a field you want to restrict, before it is restricted, then it can't be restricted anymore (or it can?). This is the code i tried:

public static void main(String[] args) {

    CanAccess.getInteroField();

    try {
        Reflection.registerFieldsToFilter(Main.class, "intero");
    } catch (Exception e) {
        e.printStackTrace();
    }

    CannotAccess.getInteroField();
}

and this is the content of getInteroField() in those 2 classes:

public static void getInteroField() {
    try {
        Field interoField = Main.class.getDeclaredField("intero");
        System.out.println("CannotAccess accessed!");
    } catch (Exception e) {
        System.out.println("CannotAccess failed to access!");
    }
}

So, the output i expected was this:

CanAccess accessed!
CannotAccess failed to access!

BUT the result i get is this:

CanAccess accessed!
CannotAccess accessed!

And if i comment the CanAccess.getInteroField(), the CannotAccess really cannot access.

So, all i need is a way to filter a field after it has been accessed.





c# constructor get 'base' part with reflection

I'm currently trying to parse public member of some random dll, i'm stuck in getting the base part of constructor with the reflection

public class MyClass: MySuperClass
 {
   public MyClass(Color color1, Color color2)
          : base(0.0f, 0.0f, 0.0f, 0.0f, color1, color2)
        {
           //...
        }
  }

From the Type i figure it how to get the constuctor and the parameters but not the call to parent class constructor ': base(0.0f, 0.0f, 0.0f, 0.0f, color1, color2)'

var MyType = typeof(MyClass);
foreach (ConstructorInfo MyConstructor in MyType.GetConstructors())
{
     var MyParameters = MyConstructor.GetParameters();

     //todo get base parameters ': base(0.0f, 0.0f, 0.0f, 0.0f, color1, color2)' ? 
}

Do you know if there is a way to get the list of parameters/value used in the parent constructor call ?





How to get only data (exported) fields from protobuf struct with reflect?

My proto file look like this

message DeviceOption {
  string ApID = 1;
  string Other = 2;
}

After run protoc, the DeviceOption struct generated like this:

type DeviceOption struct {
    state         protoimpl.MessageState
    sizeCache     protoimpl.SizeCache
    unknownFields protoimpl.UnknownFields

    ApID  string `protobuf:"bytes,1,opt,name=ApID,proto3" json:"ApID,omitempty"`
    Other string `protobuf:"bytes,2,opt,name=Other,proto3" json:"Other,omitempty"`
}

Now, in server I wanna parse all available fields using https://pkg.go.dev/reflect. My code is like:

v := reflect.ValueOf(pb.DeviceOption{
            ApID: "random1",
            Other: "random2",
        }) 
for i := 0; i < v.NumField(); i++ {
    // Do my thing
}

v.NumField() returns 5, which means it includes all the fields, including state, sizeCache, unknownFields which we don't want. We just want ApID and Other.

Is there any other way to let reflect return only data (exported) fields, and ignore metadata (unexported) fields?





How to get the class name of a polymorph C++ Object using WIN32 Debug Info API?

The win32 debugger shows the class name in question in the inspector window that means the information must be available, it's only in question wether the microsoft developers made the function public.

For Debug/Diagnostic/development purpose i wanna write a function to get the instanciated class name of a c++ object as an output and as an input the pointer to the base class.

For example:

const char* GetNameOfInstanciatedClassByVoidPtr(void* pBaseClassOrInstanciatedClass);

class B { public: B(){
  assert(StringIsEqual(GetNameOfInstanciatedClassByVoidPtr(this), "C")); } };
class C : B {} c; 

So please provide a solution for implementation of function GetNameOfInstanciatedClassByVoidPtr.

So question is: Whats the required lib/header/function ? I guess a API for the win32 Debug info would help?

Writing virtual functions which return strings or type_info is not an acceptable solution in my situation.

As i said before: this is for diagnostic/debug/development purpose only, NOT for production code so please avoid discussions about clean code purposes. I could also collect the information manually but since it's about 260 classes i might be faster this way. ;)

EDIT: As i observed the information is not yet available in the constructor time. But i have a Init method which is always called. In this method the debugger shows the name of the instanciated class so if i put the function GetNameOfInstanciatedClassByVoidPtr into my init method the information can be obtained.





mercredi 28 juillet 2021

Cast AnnotatedElement to a class type

i wanted to know how i can improve the current code or if there is a more effective/cleaner way to cast the AnnotatedElement return to a class type instead of making a method for every type ex asClass, asMethod, etc...

protected AnnotatedElement create() {
    if (type == Type.CLASS) {
        return new ClassFinder(name).get(); // Return Class
    } else if (type == Type.CONSTRUCTOR) {
        return new ConstructorFinder(name).get(); // Return Constructor
    } else if (type == Type.METHOD) {
        return new MethodFinder(name).get(); // Return Method
    }  else {
        throw new IllegalStateException();
    }
}


public Class<?> asClass() {
    return (Class<?>) create();
}

public Constructor asConstructor() {
    return (Constructor) create();
}

public Method asMethod() {
    return (Method) create();
}




How to automaticaly apply modifications to all/some fields of a case class in scala?

I'm currently challenging myself to skill up in Scala and FP. And today:

  • I came up with an issue that might interest you, devil prog masters ;)

Let's say I have the following case class in scala 3:

type EmailAddress = String // I defined them like that to show I'm interested in
type PhoneNumber = String // ... attributes via their names, not via their types.
case class Person(name: String, emails: List[EmailAddress], phones: List[PhoneNumber])

I would like to have a method that automatically transform (almost) all fields. For example, I would like to order emails with the default given instance of Ordering[String] and phones with a specified one. Ideally I should be able to exclude name field.

So I would get something like:

/* Below, I represented the kind of parametrization I would like to be able to do 
 * as parameters of the method orderValues,
 * but it could be annotations or meta-programming instead.
 * 
 * An `orderedPerson` can be directly an instance of Person
 * or something else like an OderedEntity[Person], I don't care so far.
 */
val orderedPerson =
  person.orderValues(
    excluded = Set("name"),
    explicitRules = Map(
      // Phones would have a special ordering (reverse is just a dummy value)
      "phones" -> Ordering.String.reverse
    )
  )

// -----

// So we would get:
Person(
  name = "Xiao",
  emails = List("a@a.a", "a@a.b", "a@b.a"),
  phones = List("+86 100 9000 1000", "+86 100 2000 1000")
)

I haven't used Reflection for a long time and I'm not yet familiar with Meta-Programming, but I'm open to any solution that can help me to achieve that. It's a good opportunity for learning !





The current state of reflection in C++20

I started reading about reflection in C++20 and got quite confused. What is the current state of it, i.e. how much can we use as of now?

I've found reflection TS - but even the examples on this website fail to compile (on GCC11 with C++20) because the compiler cannot find "#include <experimental/reflect>"... So it's not exactly in the GCC?

So my question is: can we use anything of reflection now, without waiting for C++23? By 'anything' I mean for example querying the compiler for list of class members, names of enums etc? And by 'use' I mean in production code, not just for playing around.





mardi 27 juillet 2021

Issues with a separate java dependency using reflection access deemed illegal in Java 16

I am trying to use some code from another java project that was originally compiled in Java 8. My current project is compiled with Java 16. I can compile the other java project in Java 16, with the --add-opens and --illegal-access=permit vm options as suggested here.

After including the compiled .jar into my project, and making a call to one of its functions, I receive an error related to reflection access that doesn't seem to be allowed in Java 16. This is the error I get (with some parts ):

Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field int java.util.regex.Matcher.<redacted> accessible: module java.base does not "opens java.util.regex" to unnamed module

The code from the other .jar that seems to cause this is here:

<redacted>.setAccessible(true);

I've added the following VM options when building but it doesn't seem to resolve the issue:

--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --illegal-access=permit

How does one get around the issue of another java project using reflection deemed illegal in Java 16? Thanks





How to read third-party console logs dynamically in code

I'm writing a Java app that uses a third-party library; this library emits useful warning messages to the console when things go wrong. So useful, in fact, that I'd like my code to act on them at the time they are produced (or shortly afterwards). Is this possible given the fact that I have no control over how the third-party library's logs are produced?

My best Googling has turned this up so far, which looks promising; but I don't know anything about PrintStream or whether the third-party library uses it for logging.

Is there some sort of equivalent to reflection whereby an application can process its own logs?





lundi 26 juillet 2021

Replacing a class field's value via IL

In my effort to learn and understand IL I'm trying to replace the value of a private field in an object, however it's not working.

public class Example
{
    private int _value;
}

private delegate void _memberUpdaterByRef(ref object source, object value);
private _memberUpdaterByRef GetWriterForField(FieldInfo field)
{
    // dynamically generate a new method that will emit IL to set a field value
    var type = field.DeclaringType;
    var dynamicMethod = new DynamicMethod(
        $"Set{field.Name}",
        typeof(void),
        new Type[] { typeof(object).MakeByRefType(), typeof(object) },
        type.Module,
        true
    );

    var gen = dynamicMethod.GetILGenerator();

    var typedSource = gen.DeclareLocal(field.DeclaringType);
    gen.Emit(OpCodes.Ldarg_0); // Load the instance of the object (argument 0) onto the stack
    gen.Emit(OpCodes.Ldind_Ref); // load as a reference type
    gen.Emit(OpCodes.Unbox_Any, field.DeclaringType);
    gen.Emit(OpCodes.Stloc_0); // pop typed arg0 into temp

    gen.Emit(OpCodes.Ldloca_S, typedSource);
    gen.Emit(OpCodes.Ldarg_1); // Load the instance of the object (argument 1) onto the stack
    gen.Emit(OpCodes.Unbox_Any, field.FieldType);
    gen.Emit(OpCodes.Stfld, field);

    gen.Emit(OpCodes.Ldarg_0); // Load the instance of the object (argument 0) onto the stack
    gen.Emit(OpCodes.Ldloc_0); // push temp
    gen.Emit(OpCodes.Box, field.DeclaringType);
    gen.Emit(OpCodes.Stind_Ref); // store object reference
    gen.Emit(OpCodes.Ret); // return void

    // create a delegate matching the parameter types
    return (_memberUpdaterByRef)dynamicMethod.CreateDelegate(typeof(_memberUpdaterByRef));
}

Given the following pseudo-code, the private field named _value does not change:

// field = Example._value
var writer = GetWriterForField(field);
writer(ref newInstance, 100); // Example._value = 0

I'm not really sure how to debug this, or what is incorrect about my IL syntax. I'm pretty much learning IL and grabbing bits from different sources trying to get this to work.





C# dynamic delegate arguments

An external library calls my code using

Delegate.Method.Invoke(Delegate.Target, new object[]{"arg1", new SomeObject()...});

or

Delegate.DynamicInvoke(new object[]{"arg1", new SomeObject()...});

(I have both options available)

I am not able to modify the code of the external library.

I need to make a delegate that receives that Object array as an argument. Note: I do not know the size or the types of the object array, but I could get it dynamically (in a System.Type array).

Example environment:

public class Program
{
    public static void Main()
    {
        // Create the delegate, can modify this part.
        var target = new Program();
        var methodInfo = typeof(Program).GetMethod("Log");
        var parameters = methodInfo.GetParameters().Select(p => p.ParameterType).ToList();
        Type type;
        
        if (methodInfo.ReturnType != typeof(void))
        {
            parameters.Add(methodInfo.ReturnType);
            type = Expression.GetFuncType(parameters.ToArray());
        }
        else
            type = Expression.GetActionType(parameters.ToArray());
        var test = Delegate.CreateDelegate(type, target, methodInfo.Name);
        
        // invoke the delegate.
        Invoke(test);
    }

    // Cant modify this method
    public static object Invoke(Delegate dDelegate)
    {
        // the array is not always the same size
        return dDelegate.DynamicInvoke(new object[]{"cheese"});
    }

    // Can modify this method and its signature
    // This does not work, "Run-time exception (line 33): Object of type 'System.String' cannot be converted to type 'System.Object[]'."
    public void Log(params object[] test)
    {
        Console.WriteLine(test[0].ToString());
    }
}

Is this even possible? If not, is there a workaround?





Reflect set bean Field

Bean

@Service
public class BeanClass{
    private String myField;
}

use

public static void doSomething(ApplicationContext applicationContext){
    Object bean = applicationContext.getBean("beanClass");
    set(bean, AopUtils.getTargetClass(object).getFields[0], "hello")
}

public static void set(Object bean, Field field, Object value){
    if(bean == null || field == null){throw new RuntimeException();}
    field.setAccessible(true);
    field.set(bean, value);
}

The above throws the Exception

Caused by java.lang.IllegalArgumentException: Can not set java.lang.String field my.package.BeanClass.myField to null value

How to set Field of a Spring bean using Reflect?

I can confirm that none of the parameters are null... which shouldnt affect it anyway because I should be able to set an reference types to null.





How to get static readonly property using reflection in some class

With the code block below, I am getting static variables of a class and the value of that variable.

static void Main(string[] args)
{
    var ax = GetClassPropertyValues("SomeClass");
}

public static List<string> GetClassPropertyValues(string className)
{
    var fieldInfos = Type.GetType($"ConsoleApp1.{className}, ConsoleApp1")
        .GetFields(
            BindingFlags.Instance
            | BindingFlags.Public
            | BindingFlags.FlattenHierarchy
            | BindingFlags.Static
        );

    var propertyValues = new List<string>();

    foreach (var fieldInfo in fieldInfos)
    {
        propertyValues.Add(fieldInfo.GetValue(null).ToString());
    }

    return propertyValues;
}

Classes

public abstract class SomeAbstractClass
{
    public static string List = "List";
}

public class SomeClass: SomeAbstractClass
{
    public static string Price = "Price";
}       

When I just set static variables to read-only then I don't get those variables. How can I get these variables ?





How to load exe with reflection if exe does not have a manifest?

I have a dump of an executable file (Runtime: v2.0.50727). It works well without any mistakes. I could load it to DnSpy to debug or to ILSpy. Both of them tells that all references successfully resolved.

However, I can't load it using this code:

try
{
    var second_module = System.Reflection.Assembly.LoadFrom("myprog.bin");
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

It gives me the following error:

System.BadImageFormatException: Could not load file or assembly 'file:///myprog.bin' or one of its dependencies. The module was expected to contain an assembly manifest.
File name: 'file:///myprog.bin'
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at myproggg.Program.Main(String[] args) in c:\Sources\My\myproggg\Program.cs:line 11

=== Pre-bind state information ===
LOG: Where-ref bind. Location = myprog.bin
LOG: Appbase = file:///c:/Sources/My/myproggg/bin/x86/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: c:\Sources\My\myproggg\bin\x86\Debug\myproggg.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Attempting download of new URL file:///c:/Sources/My/MPCExtractor/examples/MP/myprog.bin.
ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.

I tried to do these steps:

  1. Changing compile option from "Any CPU" to "x86". No difference.

  2. Changing framework to 2.0 and to 4.5. No matter what framework I use, it anyway asks me about manifest.

Nothing of the above helped me.

What can I do more to load this dumped executable?





c# Enumerate List to map parentId's from a folder structure

I have a List that contains this class:

public class RazorTree
{
    public int id { get; set; }
    public string Name { get; set; }        
    public string Path { get; set; }
    public int? parentId { get; set; } = null;
}

Example:

id = 1
path = "C:\\Projects\\testapp\subdirectoy\\"
name = "root"
parentId = null

id = 45
path = "C:\\Projects\\testapp\subdirectoy\\test.razor"
name = "test"
parentId = null

id = 55
path = "C:\\Projects\\testapp\subdirectoy\\subdirectory2\\test.razor"
name = "test"
parentId = null

What i need is that the entry with id = 45 should have parentId = 1 and id = 55 should have parentId = 45 depending on the path that each entry has.

How can i link the children with their respective parent based on the path each one has?

enter image description here





dimanche 25 juillet 2021

C# System.Reflection changing modifiers

I have a protected field or property in some class. How do I make it public(change modifier in general) using System.Reflection?





samedi 24 juillet 2021

Why do I get Java.lang.IllegalArgumentException: wrong number of arguments while creating new instance with private constructor using reflection

java.lang.IllegalArgumentException: wrong number of arguments
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at beans.ClientTest.main(ClientTest.java:14)

i am trying to invoke private constructor with newInstance() method using reflection. Here is the code.


public class Test {
    private String name;
    private int id;
    
    private Test() {
        System.out.println("private constructor.. Test");
    }

    public Test(int id) {
        super();
        this.id = id;
    }

    public Test(String name, int id) {
        super();
        this.name = name;
        this.id = id;
    }

    public Test(String name) {
        super();
        this.name = name;
    }
}

import java.lang.reflect.Constructor;

public class ClientTest {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        
        try {
            Class cl = Class.forName("beans.Test");
            Constructor[] c =  cl.getDeclaredConstructors();
            c[0].setAccessible(true);
            c[0].newInstance();
            
            for(Constructor cnt : c) {
                System.out.println(cnt);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}




vendredi 23 juillet 2021

Why I can't access to field class using reflection?

I use java spring for my project. I try to access the property and set it with a specific value using the reflection.

I try to access the name property of User class:

@Data
public class User {
    @Id
    private String id;
    private String name;
    private String phone;
    private String email;
}

Here how I try to access the name field:

User newUser = userRepository.get(id); 
User user = accessProp(newUser, User.class, "name", "John");


public <D> D accessProp(Class<D> dest, String fieldName, Object value ){
    Field filed = null;
    var cls = AdminUser.class;

    filed = cls.getField(fieldName);
    filed.set(dest, value);

    return dest;
}

But on this row:

 filed = cls.getField(fieldName);
 

I get this error:

 java.lang.NoSuchFieldException: name
 

My question is why "name" field not found?





Use reflection to loop over all available Icons

Flutter provides an Icons class which defines a long series of available icons:

https://api.flutter.dev/flutter/material/Icons-class.html#constants

I need the user to be able to set the icons for certain icon buttons, and I want to offer them a list of possibilities to chose from. Is it possible to generate such a list of IconData by somehow iterating over the static constants of the Icons class?





Given Array.Cast

TL;DR - I would expect these all to work the same, but (per comments) they do not:

var c1 = new[] { FileMode.Append }.Cast<int>();
var c2 = new[] { FileMode.Append }.Select(x => (int)x);
var c3 = new[] { FileMode.Append }.Select(x => x).Cast<int>();

foreach (var x in c1 as IEnumerable)
  Console.WriteLine(x); // Append (I would expect 6 here!)

foreach (var x in c2 as IEnumerable)
  Console.WriteLine(x); // 6

foreach (var x in c3 as IEnumerable)
  Console.WriteLine(x); // 6

This is a contrived example; I obviously wouldn't cast the collections to IEnumerable if I didn't have to, and in that case everything would work as expected. But I'm working on a library with several methods that take an object and return a serialized string representation. If it determines via reflection that the object implements IEnumerable, it will enumerate it and, in almost all cases, return the expected result...except for this strange case with Array.Cast<T>.

There's 2 things I could do here:

  1. Tell uses to materialize IEnumerables first, such as with ToList().
  2. Create an overload for each affected method that takes an IEnumerable<T>.

For different reasons, neither of those is ideal. Is it possible for a method that takes an object to somehow infer T when Array.Cast<T>() is passed?





Applying global filtering to all the classes that are inheriting from a base class in ASP.NET Entity Framework Core

I am trying to implement a global filtering for some entities that are inheriting from a BaseEntity. And I want this filtering to be somehow automatic. So what I am doing is: I am getting all the inheriting classes:

IEnumerable<BaseEntity> exporters = typeof(BaseEntity)
            .Assembly.GetTypes()
            .Where(t => t.IsSubclassOf(typeof(BaseEntity)) && !t.IsAbstract)
            .Select(t => (BaseEntity)Activator.CreateInstance(t));
            List<BaseEntity> listEntities = exporters.ToList<BaseEntity>();

Until here it is working I am getting all the sub-classes. Now I want to apply some filter on those classes, but I can't find a way to achieve that. Based on the below code:

builder.Entity<Might need some Reflection here to get the class>().HasQueryFilter(p => !p.IsDeleted);

Not so sure if it something doable or should I go on the manual way?





C# error CS0266: Cannot implicitly convert type 'System.Array'

I want to create a function to dynamic allocate array member element. The array's sizes are different and they get from a file. I use reflection to get array member element from struct object and assign it with the new array created from Array.CreateInstance() function.

private static void initArray<T>(ref T item, BinaryReader br){
var fields = item.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
//....
// get array field from object
//...
 arrayType = arrayFieldInfo.FiledType;
 int length = br.ReadInt32();
 Array arr = Activator.CreateInstance(arrayType, length) as Array;
 arrayFieldInfo.SetValue(item, arr); // this code not work
}

I found that the function not work because of this error: error CS0266: Cannot implicitly convert type 'System.Array'. Please help me.





Why doesn't reflect.Type{}.Implements(reflect.TypeOf(Interface(nil))) work?

The title is a little hard to parse so here's more verbose, understandable example:

import "fmt"
import "reflect"

type Stringer interface {
    String() string
}

type MyInt int

func (m MyInt) String() string {
    return fmt.Sprintf("I'm number %d!", m)
}

func main() {
    var m = MyInt(10)
    m_type := reflect.TypeOf(m)

    m_type.Implements(reflect.TypeOf(Stringer(nil))) // This does not work.
}

If you try this code, you will get a panic from within reflect.[some internal class].Implements. Why doesn't this work? Is this some weird side effect of typed nil and nil interfaces?

What's the best workaround for it? I've seen this in the wild:

m_type.Implements(reflect.TypeOf((*Stringer)(nil).Elem())) // true

It works, but it's ugly as hell. Is there a cleaner way? Why does this work when the naive approach does not?





@objc write runtime really works?

Can I write @objc field in Swift runtime or not?

This post says, I can, but not sure:

How to set a member variable value using reflection in Swift?

It says with @objc, reflection is possible in Swift, but in my code I can not assign, it raise error for me:

Value of type 'Organization' has no member 'setValue'

if let o = obj as? Organization {
    o.setValue(value, forKey: key)
}

I applied @objc for many field in Organization. What is the problem?

final class Organization: Model, Content {
    static let schema = "Organization"
    
    @ID(custom: "id", generatedBy: .random)
    var id: UUID?

    @OptionalField(key: "fbId")
    var fbId: String?
    
    @OptionalField(key: "name")
    @objc var name: String?




How to convert to Codable in Swift?

Organization is a Codable class:

final class Organization: Model, Content {
    static let schema = "Organization"
    
    @ID(custom: "id", generatedBy: .random)
    var id: UUID?

I have this method:

func aaa(obj: Any, keyPath: [String], value: Any) {
    if keyPath.count == 1 {
        let key = keyPath.first
        if let o = obj as Organization {
            o.setValue(value, forKey: key)
        }
        
    } else {
        var keyPath2 = keyPath
        let key = keyPath2.removeFirst()
        let t = type(of: obj)
        let mirror = Mirror(reflecting: t)
        let obj2 = mirror.children.filter{$0.label == key}.first?.value
        aaa(obj: obj2!, keyPath: keyPath2, value: value)
    }
}

4th line

if let o = obj as Organization {

raise

'Any' is not convertible to 'Organization'

Do you have any idea how to fix? How to pass obj into aaa method? Is it any more high level type than Any?





Create

I'm new in the Reflection field, and I really need some guidance, need to convert a small block of code to be valid for runtime.

This part is done currently manual:

Telegram ReqInstance = new Telegram();
Telegram ResInstance = await comm.SendMethodAsync<Telegram>(ReqInstance)

But I need to do this at runtime, The first part I've managed to do it (creating the instance) but I don't know how to call the await part

Type type = typeof(Telegram);
Assembly assembly = Assembly.GetAssembly(type);
Object instance = Activator.CreateInstance(assembly.FullName, "Telegram").Unwrap();




How can I dynamically check if type implements an interface

Assuming I have an interface called Hello like:

type Hello interface {
   Hi() string
}

I want to write a function that get Hello and any interface and does something if Hello also implement another interface, like:


type Person interface {
  Name() int
}

type Animal interface {
  Leg() int
}

type hello struct{}

func (h hello) Hi() string {
    return "hello!"
}

func (h hello) Leg() int {
    return 4
}

func worker() {

   h := hello{}
  // Don't match
  check(h,(Person)(nil))
  // Match
  check(h,(Animal)(nil))

}

func check(h Hello, n interface{}) {
 // of course this doesn't work, should I use reflection, if so how?
  if _,ok := h.(n); ok {
  // do something 
  }
}

How should I implement check function?





Discovering the NullabilityInfo of a generic parameter?

I have successfully read and used the NullableAttribute/NullableContextAttribute (based on https://github.com/dotnet/roslyn/blob/main/docs/features/nullable-metadata.md and too much trial and errors) for properties, fields and method parameters.

However, I'm failing to analyze the nullabilities of a generic parameter. My goal is to obtain the nullability information of the IA type parameter (the tuple):

interface ICommand<T> { }

interface IA : ICommand<(string,List<string?>?)> { }

However, the Nullable and NullableContext attributes are clearly not enough. The code below dumps these attributes on the type tree:

        [Test]
        public void type_in_generic_definition()
        {
            var b = new StringBuilder();
            Dump( typeof( IA ), b, Environment.NewLine );
            Dump( typeof( IA ).GetInterfaces()[0], b, Environment.NewLine );
            Console.WriteLine( b );
        }

        void Dump( Type type, StringBuilder w, string newline )
        {
            newline = newline + "  ";
            w.Append( type.Name ).Append( newline );
            var p = GetNullableProfile( type );
            w.Append( $"Nullable: {(p != null ? string.Join( null, p.Select( v => v.ToString() ) ) : "null")}" ).Append( newline );
            var c = GetNullableContextValue( type );
            w.Append( $"NullableContext: {(c != null ? c.ToString() : "null")}" ).Append( newline );
            var d = GetNullableContextValueFromDeclaringType( type );
            w.Append( $"NullableContext (DeclaringType): {(d != null ? d.ToString() : "null")}" ).Append( newline );
            if( type.IsGenericType )
            {
                foreach( var sub in type.GetGenericArguments() )
                {
                    Dump( sub, w, newline );
                }
            }
            newline = newline.Substring( 0, newline.Length - 2 );
            w.Append( newline );
        }

        byte[]? GetNullableProfile( Type t )
        {
            var a = t.CustomAttributes.FirstOrDefault( a => a.AttributeType.Name == "NullableAttribute" && a.AttributeType.Namespace == "System.Runtime.CompilerServices" );
            if( a == null ) return null;
            object? data = a.ConstructorArguments[0].Value;
            Debug.Assert( data != null );
            if( data is byte b ) return new[] { b };
            return ((IEnumerable<CustomAttributeTypedArgument>)data).Select( a => (byte)a.Value! ).ToArray();
        }

        byte? GetNullableContextValue( Type t )
        {
            var a = t.CustomAttributes.FirstOrDefault( a => a.AttributeType.Name == "NullableContextAttribute" && a.AttributeType.Namespace == "System.Runtime.CompilerServices" );
            return a == null
                    ? null
                    : (byte)a.ConstructorArguments[0].Value!;
        }

        byte? GetNullableContextValueFromDeclaringType( Type t )
        {
            var parent = t.DeclaringType;
            while( parent != null )
            {
                var found = GetNullableContextValue( parent );
                if( found.HasValue ) return found;
                parent = parent.DeclaringType;
            }
            return null;
        }

This gives me this description that doesn't make any sense (at least to me) regarding the actual nullabilities of (string,List<string?>?) (I've commented the lines after the //).

    IA
      Nullable: null
      NullableContext: null
      NullableContext (DeclaringType): 1       // I'm working in a NRT aware context where 
                                               // reference types are by default not annotated
                                               // (not null). Ok.
      
    ICommand`1
      Nullable: null
      NullableContext: 2                       // Q0: On what scope does this apply?
      NullableContext (DeclaringType): 1       // Ok. It's my context.
      ValueTuple`2                             
        Nullable: null                         // Ouch! I was expecting a "122" here :(
        NullableContext: null
        NullableContext (DeclaringType): null
        String
          Nullable: 0                           // Q1: Explicit oblivious here. Was expecting 1!
          NullableContext: 1                    // Q2: Scope? Is it the 1 I'm after?
          NullableContext (DeclaringType): null
          
        List`1
          Nullable: 0                           // The same as the string!
          NullableContext: 1                    // But the list IS nullable!
          NullableContext (DeclaringType): null
          String
            Nullable: 0                            // The inner string is nullable :(
            NullableContext: 1
            NullableContext (DeclaringType): null

Where should I look for this? What did I miss?





C# How to map files from an external project in a treeview

I want to map a external project files in a treeview with reflections.

The external project that i want to map into a treeview goes as following:

TreeStructure

How do i load this information from an external project into something i can use reflection on? I also only want to keep the files that has .razor extension.

To give you guys some context. I want to build an translation application so that you can load the razor pages from an external solution and make a json file that corresponds with each razor page.

Example: translate.nl.json

{
  "She/Center": {
    "cases":  "gevallen"
  },
  "She/Pages/Example2": {
    "title": "titel"
  }
}




jeudi 22 juillet 2021

Different behave of usual struct and struct created by reflection golang

I need a pointer to a struct for function that fills struct's fields. An usual expression a = &A{} has type *main.A and works perfect. Another way is to create an empty struct with reflect:

type A struct {
    Name string
}

a2 := reflect.New(reflect.TypeOf((*A)(nil)).Elem()).Elem().Interface()
a2_ := &a2
fmt.Printf("a2 type : %T\na2Ptr type : %T\n", a2, a2_) //OUTPUT: main.A; *interface{}

So a and a2 have same type main.A. But theirs pointers have different type (*main.A and *interface{}). Why do a and a2 behave differently when i point them despite the same type? How to make their behave the same?

Function that accepts pointer to a struct: https://play.golang.org/p/Jt1Z6a3ZRMR





C# Reflection get method input classes containing RegularExpressionAttribute s [duplicate]

Trying to find a way to fetch API's controller methods that take model classes as input parameters, which contain [RegularExpression] attributes. Any idea?





Cannot get Annotation with Reflection Java

I tried to put annotation to method and the retrieve the data inside it, but when I debug the code, I cannot get any annotations present.

This is may DatabaseSeederImpl, simple class that calls different services to seed data into database.

@Override
    public void seed() {
        seedData(SeedUserDto.class, userService);
        seedData(SeedCategoryDto.class, categoryService);
        seedData(SeedProductDto.class, productService);
    }

    private <S> void seedData(Class<?> dtoType, S service) {
        Arrays.stream(service.getClass().getDeclaredMethods())
                .filter(method -> method.isAnnotationPresent(Seed.class))
                .forEach(method -> {
                    try {
                        String fileName = method.getDeclaredAnnotation(Seed.class).fileName();
                        method.invoke(service, gson.fromJson(readJson(fileName), dtoType.arrayType()));
                    } catch (IllegalAccessException | InvocationTargetException | IOException e) {
                        e.printStackTrace();
                    }
                });
    }

This is my annotation which targets methods and its retention policy is set to runtime.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Seed {
    String fileName();
}

And in my services, I set this annotation with proper value.

@Override
@Transactional
@Seed(fileName = "categories.json")
public void seedCategories(SeedCategoryDto[] categoryDtos) {
    if (categoryRepository.count() == 0) {
        List<Category> categories = Arrays.stream(categoryDtos)
                .filter(dataValidator::isValid)
                .map(dto -> modelMapper.map(dto, Category.class))
                .collect(Collectors.toList());

        categoryRepository.saveAll(categories);
    }
}

And this is my directory tree.

Directory Tree





mercredi 21 juillet 2021

How do I convert a Linq expression to a Func<> to use?

I have built an expression tree which seems to result in an expression of type Expression<Func<object, bool>> and a return type bool which I think is what I want. But when I try to compile it into a Func<object, bool> I am getting the following System.ArgumentException:

"Expression of type 'System.Func`2[System.Object,System.Boolean]' cannot be used for return type 'System.Boolean"

My end goal is to create a return a function I can use on different objects where I know the property name and test if the property satisfies a certain condition. I don't understand why the final step is failing because from the exception it seems like I do have the anticipated Expression<Func<object, bool>> and I would think it can be used with return type bool. Here is the code:

public delegate Expression ComparisonExpressionDelegate(Expression property, Expression value);
public class ConditionCompiler
{
    public class TestClass
    {
        public string StringProperty1 { get; set; }
        public string StringProperty2 { get; set; }
        public string StringProperty3 { get; set; }
        public int IntProperty1 { get; set; }
        public double DoubleProperty1 { get; set; }
    }
    public static Func<object, bool> Test() //This is called
    {
        PropertyInfo property = typeof(TestClass).GetProperty(nameof(TestClass.StringProperty1));
        object value = "1";
        return CompileExpression(property, value);
    }
    public static Func<object, bool> CompileExpression(PropertyInfo property, object value)
    {
        ParameterExpression obj = Expression.Parameter(typeof(object), "obj");
        Expression resultExpression = CreateExpression(property, value);
        Func<object, bool> resultLambda
            = Expression.Lambda<Func<object, bool>>(resultExpression, obj).Compile(); //Issue is here
        return resultLambda;
    }

    public static Expression CreateExpression(PropertyInfo property, object value)
    {
        ParameterExpression obj = Expression.Parameter(typeof(object), "obj");
        bool isGetMethodStatic = property.GetGetMethod().IsStatic;
        UnaryExpression typedTarget = Expression.Convert(obj, property.DeclaringType);
        MemberExpression memberAccess = Expression.Property(isGetMethodStatic ? null : typedTarget, property);
        UnaryExpression boxedGetter = Expression.TypeAs(memberAccess, typeof(object));
        ConstantExpression valueExpression = Expression.Constant(value);
        ComparisonExpressionDelegate comparisonExpressionDelegate = ToString_Equals_ToString_Expression;
        Expression conditionExpression = comparisonExpressionDelegate(boxedGetter, valueExpression);
        LambdaExpression conditionExpressionLambda = Expression.Lambda(conditionExpression, obj);
        return conditionExpressionLambda;
    }
    private static ComparisonExpressionDelegate ToString_Equals_ToString_Expression
        = (property, value) => Expression.Equal(
            Expression.Call(
                typeof(string),
                nameof(String.Compare),
                null,
                Expression.Call(property, "ToString", null),
                value, Expression.Constant(StringComparison.OrdinalIgnoreCase)
                ),
            Expression.Constant(0)
            );
}




Invoke Methods without using Reflection

Well, I'm trying to invoke some methods of my object using Reflection, but even though every place that I saw how to do that it is made like that, when I try it, it doesn't work. My code look like that:

using System;
using System.Collections.Generic;
using System.Reflection;

public class Program
{
    static void Main()
    {
        List <Person> myList = new List<Person>();
        myList.Add(new Person());
        myList.Add(new Person());
        InvokeMethods(myList);
    }

    static void InvokeMethods(List<Person> myList)
    {
        foreach(Person person in myList)
        {
            MethodInfo[] methods = person.GetType().GetMethods();
            
            foreach(MethodInfo method in methods)
            {
                method.Invoke(person, null);
            }
        }
    }
}

public class Person
{
    private string name;
    public string Name { get => name; set => name = value; }
    public Person()
    {
        name = "Default";
    }

    public void SetTalking()
    {
        Console.WriteLine("{0} talking...", name);
    }

    public void SetWalking()
    {
        Console.WriteLine("{0} walking...", name);
    }
}

But, when I run this, I'm getting:

System.Reflection.TargetParameterCountException: Parameter count mismatch.

So, isn't it supposed to work since my methods don't have any arguments?





Load external assemblies into new app domain and call a method of "base class"

I'm new to remoting in .NET (which I believe this is related to).

Assume that main application references a class library A which contains an abstract class with an abstract method.

Now, assume that we create an entire new project B and reference the same DLL A, make a new class that inherits the abstract class and implements the method.

Is it possible to load this new assembly into a new appdomain in the main application and create an instance only knowing the base class type?

Or is there a better way? I'm thinking of some sort of plugin system here.





How can I cycle through each member of a structure variable?

This code is just a simplified version of what I'm looking for. Generally I'd like to know how to access any type of variable, so maybe I could type horse[6] to access an int, and horse[7] to access a char as well.

#include<stdio.h>

struct horse_s{
    int age;
    int height;
    int width;
    int weight;
}horse;

struct horse_s horse_default = {1, 2, 3, 4};

int main(){
    int i;
    int a = sizeof(struct horse); //I want this to return the amount of members in the struct
    for(i = 0; i<a; i++){
        horse_1[i] = horse_default[i] + 2; //I want this to access the i-th member of the struct variable
    }

    printf("Horse age: %d\n", horse.age);
    printf("Horse height: %d\n", horse.height);
    printf("Horse width: %d\n", horse.width);
    printf("Horse weight: %d\n", horse.weight);

    return 0;
}




mardi 20 juillet 2021

What's the best way to find the getters of a class

I have a for (Field field : CLASS.getDeclaredFields())

And i want to find if every field in the CLASS have a getter method that returns its value

So i use inside that loop:

List<Field> FieldGettersNotFound = new ArrayList<>();

for (PropertyDescriptor descriptor : Introspector.getBeanInfo(CLASS).getPropertyDescriptors()){

                if (!(descriptor.getReadMethod() != null //if method is no null
 && descriptor.getReadMethod().getParameterTypes().length==0 //if method has no parameters
 && descriptor.getReadMethod().getReturnType().equals(field.getType()))){ //if method returns the same type 
                                                            //as the type of the current field in the loop

                    if (!FieldGettersNotFound.contains(field))
                        FieldGettersNotFound.add(field);

                }

                else FieldGettersNotFound.remove(field);

 }


if (FieldGettersNotFound.size()>0) throw an Exception;

Its seems fine but when it gets in a situation like this, no exception is thrown

public class RandomSituation {

private String Name;
private String LastName;

public String getName(){

    return Name;

}

}

One way of solving this problem is:

(its all the same i just added 1 if in the else)

for (PropertyDescriptor descriptor : Introspector.getBeanInfo(CLASS).getPropertyDescriptors()){

                if (!(descriptor.getReadMethod() != null && descriptor.getReadMethod().getParameterTypes().length==0
                        && descriptor.getReadMethod().getReturnType().equals(field.getType()))){

                    if (!FieldGettersNotFound.contains(field))
                        FieldGettersNotFound.add(field);

                }
                else { 
                    if (descriptor.getReadMethod().getName().equalsIgnoreCase("get"+field.getName()))
                          FieldGettersNotFound.remove(field);

                     }
           }

But some psychopaths may call their method returnName() or something like this

Is there any better way of checking if a class have a getter method for all its fields?





Defining an unspecified type to a static variable inside of a class

I am making a simple and specific file for use in several of my projects so I need to be able to simply 'Plug and play' so-to-say.

Working with MongoDB (I don't want comments about swapping to different storage solutions.), I am fetching a collection with type to cast to, however storing it within the actual class locally rather than passing it as a return method.

public static IMongoCollection<object> ConnectedCollection;
public async Task Connect<TDoc>(string ConnectionString, string Database, string Collection)
{
    //Do some stuff here;
    //some more stuff;
    //Get collection here: 
    var MongoCollection = ConnectedDatabase.GetCollection<TDoc>(Collection);
    /// MongoCollection returns a collection of TDoc, as specified within the method,
    /// now to cast it to a static variable defined outside of the method
    ConnectedCollection = MongoCollection;
}

For obvious reasons it can't be object, I need to have ConnectedCollection be of type IMongoCollection however, as it is not an actual class but a unspecified type being cast into the method, it doesn't exist, How would I allow it to remain as a static collection within, without creating an accessible class for this file.





Quarkus native get the value of an annotation

I am trying to acces the value inside of an annotation when I compile my code to quarkus native using the command ./mvnw package -Pnative. I am trying to use Cucumber cli to execute to execute my code like this: Main.run("-g", "com.hellocucumber", "file:/hellocucumber.feature"). I have made some modifications to the source code to get it to work with Quarkus native compilation. My main problem is that there's this block of code Method expressionMethod = annotation.getClass().getMethod("value"); inside of the io.cucumber.java.GlueAdaptor which fails with the error java.lang.IllegalStateException: java.lang.NoSuchMethodException: io.cucumber.java.en.Given$$ProxyImpl.value() because we are trying to access the value of the annotation defined in the StepDefinition class. Here is my step definition class, as well as my feature file.

public class StepDefinitions {
    @Given("today is Sunday")
    public void today_is_Sunday() {
        //Print a message
    }

    @When("I ask whether it's Friday yet")
    public void i_ask_whether_it_s_Friday_yet() {
        //Print a message
    }
    
    @Then("I should be told {string}")
    public void i_should_be_told(String expectedAnswer) {
        //Print a message
    }
 
 }

Scenario: Sunday isn't Friday
    Given today is Sunday
    When I ask whether it's Friday yet
    Then I should be told Nope

I have tried to add the annotation classes (io.cucumber.java.en.Given, io.cucumber.java.en.And, etc) to the reflect.json and provide it to the native compilation as follows: quarkus.native.additional-build-args=-H:DynamicProxyConfigurationResources=reflect-config.json, this doesn't seem to work. I have also moved all the code I modified into an extension and tried to modify the annotations like this:

@BuildStep
    void addProxies(CombinedIndexBuildItem combinedIndexBuildItem,
                    BuildProducer<NativeImageProxyDefinitionBuildItem> proxies) {
        proxies.produce(new NativeImageProxyDefinitionBuildItem(StepDefinitionAnnotation.class.getName()));
        proxies.produce(new NativeImageProxyDefinitionBuildItem(Given.class.getName()));
        proxies.produce(new NativeImageProxyDefinitionBuildItem(When.class.getName()));
        proxies.produce(new NativeImageProxyDefinitionBuildItem(Then.class.getName()));
        proxies.produce(new NativeImageProxyDefinitionBuildItem(And.class.getName()));
        proxies.produce(new NativeImageProxyDefinitionBuildItem(But.class.getName()));
    }

This didn't work either, so finally I tried this:

@BuildStep
void transformAnnotations(BuildProducer<AnnotationsTransformerBuildItem> transformers) {


    transformers.produce(new AnnotationsTransformerBuildItem(new AnnotationsTransformer() {
        @Override
        public boolean appliesTo(AnnotationTarget.Kind kind) {
            return kind == AnnotationTarget.Kind.METHOD;
        }

        @Override
        public void transform(TransformationContext ctx) {
            AnnotationTarget target = ctx.getTarget();
            MethodInfo methodInfo = target.asMethod();
            ClassInfo classInfo = methodInfo.declaringClass();

            AnnotationInstance annotation = methodInfo.annotation(GIVEN_ANNOTATION);
            if (annotation == null) {
                return;
            }
             ctx.transform()
                    .add(create(
                            CDI_NAMED_ANNOTATION,
                            annotation.target(),
                            List.of(AnnotationValue.createStringValue("value", annotation.value().toString()))))
                    .done();
        }
    }));
}

This didn't work either. When I try to print out the method annotations, I only see the annotation class name, no values. When i execute this block of code:

Method[] method = StepDefinitions.class.getMethods();
    for (int j = 0; j < method.length; j++) {
        LOGGER.info("Method annotations: {}", method[j].getAnnotations().length);
        Annotation[] annos = method[j].getAnnotations();
        for (int i = 0; i < annos.length; i++) {
            LOGGER.info("Annotation: {}", annos[i]);
        }
    }

In quarkus dev mode, it prints:

  • Method annotations: 1
  • Annotation: @io.cucumber.java.en.Given(value="today is Sunday")

In quarkus native it prints this:

  • Method annotations: 1
  • Annotation: @io.cucumber.java.en.Given

At this point I have run out ideas on what to try, I am new to the quarkus ecosystem and I'm not sure if this is the right path to take or if there are better alternatives, I am open to any and all suggestions.





Structure detection in golang [duplicate]

I want to parse a string to struct using reflection. But problem is that we have many different structs, which vary in value of "Type" field. First of all I convert string to map of key-values as following:

input string:

"[6001]\ntype = endpoint\ncontext = internal\ndisallow = all\nallow = ulaw\nallow = law\naors = 6001\nauth = auth6001"

converted to map:

map[Name:6001 allow:ulaw law aors:6001 auth:auth6001 context:internal disallow:all type:endpoint]

Before reflection we have to choose which of structs to create. Does it exist a way to choose it without hardcoding (writing special func for each structure)?

type All struct{
    A 
    B
    C
}
type A struct {
    Type string
}
type B struct {
    Type string
}
type C struct {
    Name     string
    Type     string
    Context  string
    Disallow []string
    Allow    []string
    Aors     string
    Auth     string
}
input := "[6001]\ntype = endpoint\ncontext = internal\ndisallow = all\nallow = ulaw\nallow = law\naors = 6001\nauth = auth6001"
func getMap(input string) map[string]string {
    input := "[6001]\ntype = endpoint\ncontext = internal\ndisallow = all\nallow = ulaw\nallow = law\naors = 6001\nauth = auth6001"
    // remove spaces
    input = regexp.MustCompile(`\p{Z}|(\;\S+)`).ReplaceAllString(ex, "")
    rows := strings.Split(ex, "\n")
    m := make(map[string]string)
    // filling "Name" field
    m["Name"] = strings.Trim(regexp.MustCompile(`\[[a-zA-Z0-9]{1,}\]`).FindString(ex), "[]")
    // filling other fields
    for i := 1; i < len(rows); i++ {
        kv := strings.Split(rows[i], "=") // пара ключ-значение
        if _, ok := m[kv[0]]; ok {
            m[kv[0]] = fmt.Sprintf("%s %s", m[kv[0]], kv[1])
        } else {
            m[kv[0]] = kv[1]
        }
    }
    return m
}
    
func (a *All) fillStruct(m map[string]string) {
    a.C = Example{} // it should check m["type"] and then create the corresponding structure
    val := reflect.ValueOf(&E).Elem()
    for i := 0; i < val.NumField(); i++ {
        f := val.Field(i)
        name := under_score(val.Type().Field(i).Name) // "underscore" converts CamelCase to under_score
        if _, ok := m[name]; !ok {
            fmt.Println(name, ok)
            continue
        }
        switch f.Kind() {
        case reflect.Slice:
            f.Set(reflect.ValueOf(strings.Split(m[name], " ")))
        case reflect.String:
            f.SetString("test")
        default:
            log.Println("unsupported field type", f.Kind())
        }
    }
}




How can I create a C# IEnumerable<"ClassName"> at run time?

I'm currently creating a machine learning engine that will run certain routines that are configured in the database. I want to create a method that will handle multiple types of IEnumerable that are passed from the DB as a string. I will have already defined the class type in the project, I just want to dynamically create the IEnumerable from the string name of the class.

Updated with more info:

Below is an example of the List I want to populate using dapper (.net core).

The machine learning prediction engine requires column attributes adding to the class so it knows what to do with it. I've pretty much accepted that I won't be able to dynamically create the class, I just want to create a List<"ClassName"> dynamically to save on code. I could write a case statement for every type of List I want to create but don't really want to.

Here's the class defintion:

class PriceChange24
    {
        [LoadColumn(0)]
        public Single Volume { get; set; }
        
        [LoadColumn(1)]
        public Single PriceChange1H { get; set; }

        [LoadColumn(2)]
        public Single PriceChange24H { get; set; }

        [LoadColumn(3)]
        public Single PriceChange7D { get; set; }

        [LoadColumn(4)]
        public Single PriceChange1HAvg { get; set; }

        [LoadColumn(5)]
        public Single PriceChange24HAvg { get; set; }

        [LoadColumn(6)]
        public Single PriceChange7DAvg { get; set; }

        [LoadColumn(7)]
        public Single RSI { get; set; }

        [LoadColumn(8), ColumnName("Label")]
        public bool GreaterThan10_24 { get; set; }

        public Single Volume24H { get; set; }

        public string Symbol { get; set; }

        public Single GBPValue { get; set; }

        public DateTime LastUpdated { get; set; }

}




Unmarshal list of arbitrary struct and append it to slice with reflection

I would like to unmarshal a JSON string which will be a list of an arbitrary struct (determined at runtime), and append the unmarshalled list of structs to a slice supplied to the function (the type is unknown before runtime, but is a slice of the same time of the list being unmarshalled).

Here is a minimal example of what I'm trying to achieve (playground link here):

type Foo struct {
    Name string
}

func get(results interface{}) (interface{}, error) {
    resVal := reflect.ValueOf(results)
    data := reflect.New(resVal.Type())

    err := json.Unmarshal([]byte(`[{"name":"data"},{"name":"test"}]`), data.Interface())
    if err != nil {
        return nil, err
    }

    return reflect.Append(resVal, data).Interface(), nil
}

func main() {
    results := []Foo{}
    newResults, err := get(results)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%#v\n", newResults)
}

I believe the above should work, but I'm getting:

panic: reflect.Set: value of type *[]main.Foo is not assignable to type main.Foo




lundi 19 juillet 2021

Why in C# with reflection we can set the value of property with private set, but can not invoke the private method

GetMethod only searches the public method, but with GetProperty, we get the public auto property with a private set, and we can set the value to this property. Can somebody explain why?





Scala Reflection Test for class validation

I am completely new to scala. I have the below requirements for one use case.

I want to do some reflection tests for scala classes. The idea is to is compare the class properties and recursively check the class lineage between older version classes. The implication of that just needs to get the properties of both parent and child and make sure that there are no properties in the parent that do not exist (with same type info) on the child).

Could you please help with some sample examples?





Assign a string to a struct via reflect

I have a struct, where I wish to dynamically change a string to another string using reflect. My issue is that the new string is created on the stack, and therefore the Set() method panics.

This makes sense to me, but I don't know how to fix it. I'm not sure the easy way to declare a string as addressable or if there's a different reflection technique to use.

type MyStruct struct {
    SomeField string
}

func main() {
    myStruct := MyStruct{"initial"}
    hello := "hello world"
    
    field := reflect.ValueOf(myStruct).FieldByName("SomeField")
    helloValue := reflect.ValueOf(hello)
    fmt.Printf("hello is on the stack, canAddr is %v\n", helloValue.CanAddr())
    
    // This will panic because canAddr is false
    field.Set(helloValue)
}

https://play.golang.org/p/ghUgiQfKXhk





Merge slice of structs, dynamically

My function get takes a slice of arbitrary structs (always a slice) as the results parameter.

I want to create another slice data of the same structs, populate data, and then merge data with results.

Here's a partial implementation:

type Foo struct {
    name string
}

func get(results interface{}) {
    data = reflect.New(reflect.TypeOf(results)).Interface()
    
    // get some dataJSON string and unmarshal it
    err := json.Unmarshal([]byte(dataJSON), data)
    
    // how to append data to results?
}

func main() {
    results := []Foo{}
    get(results)
}

How can I merge data and results?





dimanche 18 juillet 2021

calling a class implementing an interface using reflections

I'm using reflections to find all classes implementing IAnimal Interface. but how do I call or return a class using the animals set in the below code:

Reflections reflections = new Reflections(IAnimal.class);    
Set<Class<? extends IAnimal>> animals= reflections.getSubTypesOf(IAnimal.class);

I have 3 classes implementing IAnimal interface Dog, Cat, Duck. and I want to apply this logic but I don't know how to do it.

    method findAnimal(String animalName){

        for (Iterator<Class<? extends Operations>> it = animals.iterator(); it.hasNext(); ) {
            String classname=it.Name;
            if (classname.eqauls(animalName)){
               System.out.println("found");
                return new class(); }
        }}

I want the findAnimal method to return a class instance if matched with the passed string. i.e., if I passed a "Dog" string as a parameter, the method will return a dog class.

is it possible to do that, any ideas on how to implement the logic in the box above?





C# Reflection GetField().GetValue()

Given the following:

List<T> someList;

Where T is a type of some class:

public class Class1
{
  public int test1;
}

public class Class2
{
  public int test2;
}

How would you use Reflection to extract the values of test1/test2 stored in each List item? (The field names are provided)

My Attempt:

print(someList[someIndex]
.GetType()
.GetField("test1")
.GetValue(someList) // this is the part I'm puzzled about. What kind of variable should i pass here?

The Error I'm getting: "Object reference not set to an instance of an object", and according to microsoft docs the variable I should pass to GetValue is "The object whose field value will be returned." - which is what I'm doing.

Thanks for reading!





samedi 17 juillet 2021

Why am I getting undefined even using bind?

    interface LooseObject {
        [key: string]: any
    }
    
    function f(obj: object)
    {
        let p:LooseObject = {};
        for (; obj != null; obj = Object.getPrototypeOf(obj))
        {
            for(var [k, v] of Object.entries(Object.getOwnPropertyDescriptors(obj)))
            {
                if(typeof v.get === 'function' && k !== '__proto__')
                {
                    const vv = v.get.bind(obj);
                    console.log('key = ', k, ', value = ', vv())
                }
            }
        }
        return p;
    }

class Foo
{
    #x;
    #y;

    constructor()
    {
        this.#x = 20;
        this.#y = 10;
    }

     get a()  { return "baa"; }
     get n()  { return 20; }
}

class B extends Foo
{ 
    get z(): number { return 30; }
}

then

let o = new B()
f(o)

but I'm getting undefined from this line const vv = v.get.bind(obj); what I missing?





Use reflection to find IConfigureOptions

I want to find all types that implement ASP.NET Core's IConfigureOptions<JsonOptions> interface.

Here is an example of such a class:

public sealed class MyJsonOptions : IConfigureOptions<JsonOptions> {
  public void Configure(JsonOptions options) { }
}

This found nothing:

AppDomain.CurrentDomain
.GetAssemblies()
.Where(assembly => !assembly.IsDynamic)
.SelectMany(assembly => assembly.ExportedTypes)
.Where(type => type.IsAssignableTo<IConfigureOptions<JsonOptions>>())
.ToArray();

I also tried this:

AppDomain.CurrentDomain
.GetAssemblies()
.Where(assembly => !assembly.IsDynamic)
.SelectMany(assembly => assembly.ExportedTypes)
.Where(type => type
  .GetInterfaces()
  .Any(x =>
    x.IsGenericType &&
    x.GetGenericTypeDefinition() == typeof(IConfigureOptions<>)))
    //&& x.GetGenericArguments()[0] == typeof(JsonOptions)  // if included then nothing found
.ToArray();

That gives me all types implementing IConfigureOptions<>. But of course I also need the typeparam JsonOptions.

How do I do this?





vendredi 16 juillet 2021

Assemlby.Load(byte[] assemblyinfo) Problem

I want to create plugin loader for some game, i send byte[] by server, accept it by client and try to Assembly.Load(byte[]), on local machine it works perfectly, but on remote computer a.k.a test server, i have exception on Assembly.Load, i need some help Image1, image2 , image3





Differences in reflection between JDK 1.8 and JDK 16

The following statement was executed in both Oracle JDK1.8 and OpenJDK 16, but the different results returned. Founded during daily developping, the confusing issue is whether the difference are intended to be so or just an obscure bug? I've already done searching the similary questions but no expected ones was founded.

Examples,

Field[] declaredFields = Field.class.getFields();
// Field[12] with all private fields which are expected. (JDK 1.8)
// Empty field array. (JDK 16)

Through debug mode, the critical statements are located: line 293, 309 in jdk.internal.reflect.Reflections. Those methods left without javadoc.

// line 293
return (Field[])filter(fields, fieldFilterMap.get(containingClass));

// line 309
if (filteredNames.contains(WILDCARD)) {
    return (Member[]) Array.newInstance(memberType, 0);
}




IllegalAccessException when trying to modify private static field

I tried to follow this Change private static final field using Java reflection

But for some reason i get java.lang.IllegalAccessException: Can not set static final java.lang.Long field DataRepositoryTests.Item.id to java.lang.Integer

for (Field field : Table.getDeclaredFields()){

                    System.out.println(Table.getSimpleName()); //prints "Item"
                    
                    field.setAccessible(true);

                    if (field.getName().equals(GeneratedValueFields.get(i).getName())) { 

                        System.out.println(field.getName()); //prints "id"

                        Field modifiersField = Table.getDeclaredField(GeneratedValueFields.get(i).getName()); 

                        System.out.println(modifiersField.getName()); //prints "id" as expected

                        modifiersField.setAccessible(true);
                        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); //error here

                        //data = 9 (Long)

                        field.set(null,data);


                    };

Now if i remove the line modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

I get java.lang.IllegalAccessException: Can not set static final java.lang.Long field DataRepositoryTests.Item.id to java.lang.Long

If i change the field to just private final and specify a Object

field.set(TableModel,data);

It works properly





jeudi 15 juillet 2021

Using Reflection to build EF Core query is faster than to using reflection

I've got an IQueryable Extension method that is being used to reduce the amount of boiler plate code needed to search a number of fields in an EF Core DbContext model:

public static IQueryable<TEntity> WherePropertyIsLikeIfStringIsNotEmpty<TEntity>(this IQueryable<TEntity> query,
    string searchValue, Expression<Func<TEntity, string>> propertySelectorExpression)
{
    if (string.IsNullOrEmpty(searchValue) || !(propertySelectorExpression.Body is MemberExpression memberExpression))
    {
        return query;
    }
    
    // get method info for EF.Functions.Like
    var likeMethod = typeof(DbFunctionsExtensions).GetMethod(nameof(DbFunctionsExtensions.Like), new []
    {
        typeof(DbFunctions),
        typeof(string),
        typeof(string)
    });
    var searchValueConstant = Expression.Constant($"%{searchValue}%");
    var dbFunctionsConstant = Expression.Constant(EF.Functions);
    var propertyInfo = typeof(TEntity).GetProperty(memberExpression.Member.Name);
    var parameterExpression = Expression.Parameter(typeof(TEntity));
    var propertyExpression = Expression.Property(parameterExpression, propertyInfo);
    
    
    var callLikeExpression = Expression.Call(likeMethod, dbFunctionsConstant, propertyExpression, searchValueConstant);
    var lambda = Expression.Lambda<Func<TEntity, bool>>(callLikeExpression, parameterExpression);
    return query.Where(lambda);
}

The code is working and producing expected results, however I was worried that I would get a performance hit for using Expressions and a bit of reflection. So I set up a benchmark using an in memory database and the BenchmarkDotNet nuget package. Here is the benchmark:

using System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Microsoft.EntityFrameworkCore;

class Program
    {
        static void Main(string[] args)
        {
            BenchmarkRunner.Run<Benchmark>();
        }
    }

    public class Benchmark
    {
        private Context _context;
        private string SearchValue1 = "BCD";
        private string SearchValue2 = "FG";
        private string SearchValue3 = "IJ";
        
        [GlobalSetup]
        public void Setup()
        {
            _context = new Context(new DbContextOptionsBuilder<Context>().UseInMemoryDatabase(Guid.NewGuid().ToString())
                .Options);

            _context.TestModels.Add(new TestModel(1, "ABCD", "EFGH", "HIJK"));
            _context.SaveChanges();
        }

        [GlobalCleanup]
        public void Cleanup()
        {
            _context.Dispose();
        }
        
        [Benchmark]
        public void FilterUsingExtension()
        {
            var _ = _context.TestModels
                .WherePropertyIsLikeIfStringIsNotEmpty(SearchValue1, testModel => testModel.Value)
                .WherePropertyIsLikeIfStringIsNotEmpty(SearchValue2, testModel => testModel.OtherValue)
                .WherePropertyIsLikeIfStringIsNotEmpty(SearchValue3, testModel => testModel.ThirdValue)
                .ToList();
        }

        [Benchmark]
        public void FilterTraditionally()
        {
            var query = _context.TestModels.AsQueryable();
            if (!string.IsNullOrEmpty(SearchValue1))
            {
                query = query.Where(x => EF.Functions.Like(x.Value, $"%{SearchValue1}%"));
            }
            if (!string.IsNullOrEmpty(SearchValue2))
            {
                query = query.Where(x => EF.Functions.Like(x.OtherValue, $"%{SearchValue2}%"));
            }
            if (!string.IsNullOrEmpty(SearchValue3))
            {
                query = query.Where(x => EF.Functions.Like(x.ThirdValue, $"%{SearchValue3}%"));
            }
        
            var _ = query.ToList();
        }
    }

    public class TestModel
    {
        public int Id { get; }
        public string Value { get; }
        public string OtherValue { get; }
        public string ThirdValue { get; }

        public TestModel(int id, string value, string otherValue, string thirdValue)
        {
            Id = id;
            Value = value;
            OtherValue = otherValue;
            ThirdValue = thirdValue;
        }
    }
    
    public class Context : DbContext
    {

        public Context(DbContextOptions<Context> options)
            : base(options)
        {
            
        }
        
        // ReSharper disable once UnusedAutoPropertyAccessor.Global
        public DbSet<TestModel> TestModels { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<TestModel>().ToTable("test_class", "test");
            modelBuilder.Entity<TestModel>().Property(x => x.Id).HasColumnName("id").HasColumnType("int");
            modelBuilder.Entity<TestModel>().Property(x => x.Value).HasColumnName("value").HasColumnType("varchar")
                .ValueGeneratedNever();
            modelBuilder.Entity<TestModel>().Property(x => x.OtherValue).HasColumnName("other_value").HasColumnType("varchar")
                .ValueGeneratedNever();
            modelBuilder.Entity<TestModel>().Property(x => x.ThirdValue).HasColumnName("third_value").HasColumnType("varchar")
                .ValueGeneratedNever();
            modelBuilder.Entity<TestModel>().HasKey(x => x.Id);
        }
    }

Like I said, I was expecting performance penalties for using reflection. but the benchmark shows that the query being built by my extension method is more than 10 times faster than just writing the expression directly in the Where method:

|               Method |        Mean |     Error |    StdDev |      Median |
|--------------------- |------------:|----------:|----------:|------------:|
| FilterUsingExtension |    73.73 us |  1.381 us |  3.310 us |    72.36 us |
|  FilterTraditionally | 1,036.60 us | 20.494 us | 22.779 us | 1,032.69 us |

Can anyone give an explanation for this?





How can I list all the get properties from a give object?

Give the class:

export class Foo
{
    #x: number;
    #y : number;

    constructor()
    {
        this.#x = 20;
        this.#y = 10;
    }

    public get a(): string { return "baa"; }
    public get n(): number { return 20; }
}

How can I get the getters properties i.e., ["a", "n"]? I have no code to show yet, I've looked reflect and reflect-metadata and I couldn't find anything to list those. I'm using typescript but javascript solutions are welcome too.





Is there a way to be recursive through different types of ProtoBuf fields?

I am trying to create a diff between protobuf messages that would work along all the IMessage objects (as far as I can tell the interface every protobuf implements) in our codebase.

To this end, I have made a generic method that would take any IMessage implementation that provides a parameterless constructor and would attempt to create a delta from such an example.

public class ProtocolDiffer<T> where T : IMessage, new()
    {
    public T Diff(T original, T replacement)
            {
                var delta = new T();
    
                foreach (var fieldDescriptor in replacement.Descriptor.Fields.InFieldNumberOrder())
                {
                    // Obtain the pair of values to compare
                    var originalFieldValue = fieldDescriptor.Accessor.GetValue(original);
                    var replacementFieldValue = fieldDescriptor.Accessor.GetValue(replacement);
                    Console.WriteLine(
                        $"Is the field {fieldDescriptor.Name.ToUpper()} equal between Original and Replacement? " +
                        $"{originalFieldValue.Equals(replacementFieldValue)}");
                    // These fields are equal, jump to the next pair
                    if (originalFieldValue.Equals(replacementFieldValue)) continue;
                    // They were not equal
                    // Is it a simple field?
                    if (fieldDescriptor.FieldType == FieldType.Message)
                    {
                        // Non-basic fields need to be evaluated instead of simply replaced
                        fieldDescriptor.Accessor.SetValue(delta,
                            Diff((T)(IMessage) fieldDescriptor.Accessor.GetValue(original),
                                (T)(IMessage) fieldDescriptor.Accessor.GetValue(replacement)));
                    }
                    else
                    {
                        fieldDescriptor.Accessor.SetValue(delta, fieldDescriptor.Accessor.GetValue(replacement));
                    }
                }
    
                return delta;
            }

The issue I am having is that the recursive mechanism fails since eventually the object being treated changes from the class we generated through protoc to a RepeatedField and the Diff will not be able to cast the objects.

I have tried using IMessage as the parameter to instanciate this Diff class but it does not provide a parameterless constructor. I am now considering creating a class that implements IMessage that would be able to be cast to by our protoc generated classes and RepeatedField but that will still take some time and I am unsure if I would even be able to provide the necessary casting in the first place.

Finally, this is all being done so that I can return the difference between two structures, including primitive fields and complex ones such as Lists, the idea being that the recursive mechanism would traverse the whole structure until it replaces every different field and then returns the structure with only those same fields set.

Is there a way to fix the casting issue so I can keep using the recursive mechanism?

Thanks in advance,





Nested string to class deserialization using YamlDotNet

I need to be able to dynamically deserialize strings (as properties) into classes during runtime. I also need to be able to do this in a way that supports nesting.

Example - Turret which shoots exploding bullets

Turret.yaml

Type: Turret
Name: MiniTurret
DisplayName: Mini Turret
MaxHP: 100
Damage: 50
TurretTurnSpeed: 20
Sprite: turret_1
ProjectileName: ExplosiveBullet

ExplosiveBullet.yaml

Type: Bullet
Name: ExplosiveBullet
DisplayName: Explosive Bullet
Damage: 50
TurretTurnSpeed: 20
Sprite: explosivebullet1
Components:
   - ExplosionComp:
      - ExplosionType: Incendiary
      - Damage: 10
      - Radius: 5

We're trying to create a turret (with the Turret.cs class, as stated in the "Type" field) that shoots projectiles with a Def name "ExplosiveBullet". At runtime, we deserialize the string "ExplosiveBullet" into it's appropriate class. The bullet now does the same with the list of Components - it needs to deserialize the string "ExplosionComp" into ExplosionComp.cs, and pass in the Damage and Radius values.

This way, I'm trying to created a nested component system which can reference other components (such as a turret referencing bullets, and a bullet referencing an explosion effect it causes when it's destroyed).

Does reflection have to be used to solve this? Is there anything built into YamlDotNet specifically to handle this?

I've seen dated or convoluted solutions; is there a good approach to handle this problem with YamlDotNet?





How to access an event in a dictionary with C#? [duplicate]

I'm trying to access an event which I have placed in a dictionary, I'd like to raise this event by selecting it from the dictionary. My event is defined as follows:

public static event EventHandler<SelectResultaatArgs> AddressSelected;

The dictionary looks as follows, which raises no build errors:

private Dictionary<string, Delegate> _eventIdentifiers = new() {
        { "AddressSelected", AddressSelected}
};

I have tried the following methods of accessing the event, both return null.

var r =_eventIdentifiers["AddressSelected"].GetMethodInfo();

and

var r =_eventIdentifiers["AddressSelected"];

I receive an event name from a different layer, which I want to use to raise a specific event from the dictionary, how could I assure that the result returned is not null?





How to subscribe to the WndProc method and receive it's parameters

I am trying to subscribe to the WndProc(ref Message m) method via reflection.

Currently, I have the next code:

Assembly winFormsAssembly = AppDomain.CurrentDomain.GetAssemblies()
                                     .FirstOrDefault(asm => asm
                                                           .FullName
                                                           .Contains("System.Windows.Forms"));

Type formType = winFormsAssembly?.GetType("System.Windows.Forms.Form");
Type messageType = winFormsAssembly?.GetType("System.Windows.Forms.Message");

MethodInfo wndProcInfo = formType.GetMethod("WndProc",
                                            BindingFlags.NonPublic | BindingFlags.Instance,
                                            null,
                                            new[] {messageType.MakeByRefType()}, null);

It is necessary to receive an event when the method was invoked and get its parameters. Please give an advise which step should be the next.





detecting if a class has been changed

I have two java API project X and Y, the project Y depends on X by using some classes declared on X, and these two projects are running on two different servers.

Now let assume that a class C of X has been changed (e.g we've added a property, changed a method ...), how can Y detect the change? is there any way or workaround to do in order to detect the changes? maybe using java reflection or using some rest calls From the API Y to X to check periodically the status ?

Thank you





mercredi 14 juillet 2021

Copy slice with reflect and usafe package

I understand that usage of usafe package of golang is unsafe, but I'm doing it only for education purposes.

The idea is to copy a slice field of structure, copy it with reflect package and unsafe.pointer, modify and replace the original slice with new one.

And it looks like new slice is created and has correct capacity/length, and it contains an instance of GoodForSale type. But all fields of that instance (Name, Price and Qnty) have wrong values. So I suppose that I'm doing something wrong with pointers and getting garbade data:

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

type GoodForSale struct {
    Name string
    Price int
    Qnty int
}

type Lead struct {
    ID int
    Name string
    ContactName string
    Budget int
    Items []GoodForSale
    DateTime string
    Status int
    Win bool
}

func main()  {
    lead := &Lead{
        ID:          41,
        Name:        "Phone",
        ContactName: "John Smith",
        Budget:      30000,
        Items:       []GoodForSale{
            {
                Name:  "Iphone 6",
                Price: 100,
                Qnty:  3,
            },
        },
        DateTime:    "12.08.2020 11:23:10",
        Status: 150,
        Win:         false,
    }


    //Change Items
    pt1 := unsafe.Pointer(&lead.Items)
    copyItems := &reflect.SliceHeader{
        Data: uintptr(pt1),
        Cap: cap(lead.Items),
        Len: len(lead.Items),
    }


    items := *(*[]GoodForSale)(unsafe.Pointer(copyItems))
    fmt.Println(items[0].Name)

}

It looks like I'm missing something about how pointers work here. But how can I make this idea work correct?

Here is a go playground url: https://play.golang.org/p/SKtJWe9RVEU





How to get the class of generic T of an interface

So i want to execute the following method, but i cannot find a way to access the Model.class and specific the Item.class

public interface DataRepository<Model> {

default List<Model> getAll() throws Exception{

    return (List<Model>) getQueryManager().getAll( -Model.class- );

}

The interface is implemented this way:

public class ItemService implements DataRepository<Item> {

public ItemService() throws Exception {

    getAll();

}

I have tried the following :

public class ItemService extends Service<Item> implements DataRepository<Item> {

public ItemService() throws Exception {

    super(Item.class);

    getAll();

}

public abstract class Service<T> {

Class<T> clazz;

protected Service(Class<T> clazz){

    this.clazz = clazz;

}

protected Class<T> getT(){

    return clazz;

};

}

And then use the getMethod("getT").invoke() method but i get NoSuchMethodException