vendredi 2 avril 2021

What's the benefit of that escape in the reflect package

// reflect/value.go

func ValueOf(i interface{}) Value {
    if i == nil {
        return Value{}
    }

    // TODO: Maybe allow contents of a Value to live on the stack.
    // For now we make the contents always escape to the heap. It
    // makes life easier in a few places (see chanrecv/mapassign
    // comment below).
    escapes(i)

The code above is the source code of Value.go in golang, and the comment above the escapes(i) shows that each time we call the ValueOf function, the i will escape to the heap, that's why? Namely, how to explain the It makes life easier in a few places?





Unexpected exception for remote running unit tests with MethodHandles

The following line of code in tests

var lookup = MethodHandles.privateLookupIn(Field.class, MethodHandles.lookup());

where Field is java.lang.reflect.Field throws a

java.lang.IllegalAccessException: module java.base does not open java.lang.reflect to unnamed module @497470ed
    at java.lang.invoke.MethodHandles.privateLookupIn(MethodHandles.java:260) ~[?:?] 

The code works fine if tests are run locally (either via IDE or maven lifecycle), but fails on maven test run on CI pipeline on a remote host.

Maven is configured for java 11, but test execution as we saw in logs was using openjdk-16 jvm.

Would appreciate any ideas on where to look.





jeudi 1 avril 2021

Object does not match target type PropertyInfo.GetValue()

Im fairly new to .net and would love to get some help with reflection. I have searched everywhere and i cant seem to get this right.

I've got a function which takes in a generic list of my custom class and i am iterating over extracting the properties of the classes and creating a spreadsheet. My issue is when i try to get the value of the property, i get an exception saying 'Object does not match the target value'.

I know this might be a duplicate but i was unable to find anything and any help would be greatly appreciated.

private static Task<SheetData> GenerateSheetDataPart<T>(List<T> data){
//some speadsheet logic

foreach (var dataModel in data){
    //some more spreadsheet logic
    Type type = dataModel.GetType();
    PropertyInfo[] props = type.GetProperties();
    foreach (var prop in props){
        cell.DataType = await ResolveCellDataTypeOnValue((string)prop.GetValue(prop)); //exception here. function returns Number or String based what value is.
        cell.CellValue = new CellValue((string)prop.GetValue(prop);
    }
}
}




Check if a class property is string compatiable?

I am using reflection to find all the string compatible properties in an object graph.

I am consuming a 3rd party's XML. They provide me with the POCO classes, but sometimes they do weird things like having a property in a class called Item that is declared as object but it can have a backing type as a string or of another of their classes.

Here is a property

/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("BuiltInScript", typeof(TypeBuiltInScript))]
[System.Xml.Serialization.XmlElementAttribute("CloseScreen", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("OpenScreen", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("ResetTag", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("SetTag", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("ToggleTag", typeof(string))]
[System.Xml.Serialization.XmlElementAttribute("VBScript", typeof(string))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
public object Item
{
    get
    {
        return this.itemField;
    }
    set
    {
        this.itemField = value;
    }
}

This is the section of my code that finds all of the properties of type string this issue it is seems to only work if the POCO class has a property declared as a string and not object

Is there a way to do a compatibility check to see if it can be cast as a string?

PropertyInfo[] proInfoForStrings = objectToEvaluate.GetType().GetProperties()
                        .Where(x => x.PropertyType == typeof(string)).ToArray();




How do I get MethodInfo of a controller action with HttpContext? (NET CORE 2.2)

I know that I have to use reflection but I don't know how. I'm trying to know the MethodInfo from a StartUp Middleware. I need the MethodInfo to know if the action that I'm invoking is or is not async.

Thank you for your time.





How to specify generic type for method dynamically in context (without reflection if possible)

So is it possible to specify a generic type for a method dynamically in C#? I am not talking about using reflection, but with just C#.

Example:

internal class MyRepository
{
  async Task<IEnumerable<WhateverClass>> GetItemsFor<T>(int entityId, int itemId, params string[] keys)
    where T : class, IEntity
  {
    // do whatever
  }
}

interface IEntity
{
  public int Id { get; set; }
}

internal class Foo : IEntity
{
  // whatever
}

Now my problem is that I will supply a string "foo" as internal class Foo because Foo is internal and cannot be accessed by my other projects (which is intended). But it is externally known as string "foo".

Now I want to call following method (which is public).

public async Task<IEnumerable<WhateverClass>> GetItemsFor(string forAsString, int entityId, int itemId, params string[] keys)
{
  var forAsType = forAsString switch
  {
     "foo" => typeof(Foo) // or what is needed here
  };

  return await _myRepository.GetItemsFor<forAsType>(entityId, itemId, keys); // this is not possible. How can I make this work?
}

Because the generic T is accessing a DbSet of type T I need to able to supply this in context.

So how can I solve this puzzle? Reflection is not forbidden but I am wondering if there is a "native" way. Or a respectable way with reflection

Edit 1:

WhateverClass has a correlation to IEntity. Let's say I want to set a bool based on if the IEntity is in a collection. This is abstracted a lot, but it is of no use to type all the context here.

public class WhateverClass
{
  public bool Enabled { get; set }
}




How to get a method's parameter values from within the method using reflection?

I have hundreds of functions, each with different names and parameters. Every time a function is called, I need to log the method name, the parameter names and the values which the client passes in via the parameters. But I don't want to write the logging code for every function. It takes a long time, and every time a function's parameters are changed the logging code needs to change too.

So I hope I can write one block of code, and insert it into the beginning of every function. This block of code uses reflection to get the method name, names of the parameters, and most importantly, the values passed into the function via the parameters.

How do I do that?