mercredi 31 mars 2021

Experimenting With Static Reflection in C++

I’m just watching the video CppCon 2017: Herb Sutter “Meta: Thoughts on generative C++” (https://youtu.be/4AfRAVcThyA )

At 15:02 there is some discussion about a topic which I understand to be “static reflection”.

I think it looks really cool, but when I try to compile the example with the g++-10 compiler it doesn’t work. Is there a special header file that I need to include to get this to work? If so, which one? Should I maybe try a different compiler ? If so, which do you recommend? Or do I have to wait for like C++23 to try some of this cool stuff out?

I’d really like to play around with this now if possible. If anyone could point me in the right direction, I’d appreciate it.

Thank you,

Dave





Can I extends hidden class?

I would like to develop test app.

I want to create class which is extended from hidden class.(Not involved Android sdk)

Actually, I can call hidden api trough reflection.

But how can I create class which is extended from hidden class?

Thanks in advance





C# reflection: how to get a function's MethodInfo FROM WITHIN THIS FUNCTION

Suppose there is a function GetEmployees:

public static List<Employee> GetEmployees(Dictionary<int, Department> depts, bool isFullTime)
{
    // How do I get the MethodInfo of this "GetEmployees" function by writing code here?
}

The reason I need to get the MethodInfo inside this function is that I need to know

  • The function name ("GetEmployees")
  • The number of parameters ("2")
  • The parameter names ("depts" and "isFullTime")
  • The parameter types ("System.Collections.Generic.Dictionary`2[int, Department]&" and "System.Boolean")
  • The return type

I am sure you will ask me, "You already have the source code of this function, it is plainly in front of you, why do you need to write code to find it out?" My answer is, "Please just trust me that I have a good reason to do so." Thanks!





netty Reflective Access Unsupported

I have an AWS Firehose Client running in my lambda fucntion. It is instantiated as shown below.

  private static FirehoseAsyncClient firehoseClient =
      FirehoseAsyncClient.builder()
          .region(Region.of(Env.getRegion()))
          .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
          .overrideConfiguration(
              ClientOverrideConfiguration.builder()
                  .apiCallAttemptTimeout(Duration.ofSeconds(3))
                  .retryPolicy(
                      RetryPolicy.builder()
                          .backoffStrategy(BackoffStrategy.defaultStrategy())
                          .retryCondition(RetryCondition.defaultRetryCondition())
                          .numRetries(10)
                          .build())
                  .build())
          .build();

When we do a PutRecord, i'm getting below exception, which is similar to the one specified here. Since it is running as a normal lambda function, i couldnt find a way to specify -Dio.netty.tryReflectionSetAccessible=true/false as specified in the other SO answer.

java.lang.UnsupportedOperationException: Reflective setAccessible(true) disabled
    at io.netty.util.internal.ReflectionUtil.trySetAccessible(ReflectionUtil.java:31)
    at io.netty.util.internal.PlatformDependent0$4.run(PlatformDependent0.java:238)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:232)
    at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:293)
    at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:92)
    at io.netty.util.ConstantPool.<init>(ConstantPool.java:32)
    at io.netty.channel.ChannelOption$1.<init>(ChannelOption.java:36)
    at io.netty.channel.ChannelOption.<clinit>(ChannelOption.java:36)
    at software.amazon.awssdk.http.nio.netty.internal.SdkChannelOptions.<init>(SdkChannelOptions.java:31)
    at software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient$DefaultBuilder.<init>(NettyNioAsyncHttpClient.java:464)
    at software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient$DefaultBuilder.<init>(NettyNioAsyncHttpClient.java:461)
    at software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient.builder(NettyNioAsyncHttpClient.java:126)
    at software.amazon.awssdk.http.nio.netty.NettySdkAsyncHttpService.createAsyncHttpClientFactory(NettySdkAsyncHttpService.java:29)
    at java.base/java.util.Optional.map(Unknown Source)
    at software.amazon.awssdk.core.internal.http.loader.DefaultSdkAsyncHttpClientBuilder.buildWithDefaults(DefaultSdkAsyncHttpClientBuilder.java:42)
    at software.amazon.awssdk.core.client.builder.SdkDefaultClientBuilder.lambda$resolveAsyncHttpClient$8(SdkDefaultClientBuilder.java:285)
    at java.base/java.util.Optional.orElseGet(Unknown Source)
    at software.amazon.awssdk.core.client.builder.SdkDefaultClientBuilder.resolveAsyncHttpClient(SdkDefaultClientBuilder.java:285)
    at software.amazon.awssdk.core.client.builder.SdkDefaultClientBuilder.finalizeAsyncConfiguration(SdkDefaultClientBuilder.java:236)
    at software.amazon.awssdk.core.client.builder.SdkDefaultClientBuilder.asyncClientConfiguration(SdkDefaultClientBuilder.java:181)
    at software.amazon.awssdk.services.firehose.DefaultFirehoseAsyncClientBuilder.buildClient(DefaultFirehoseAsyncClientBuilder.java:28)
    at software.amazon.awssdk.services.firehose.DefaultFirehoseAsyncClientBuilder.buildClient(DefaultFirehoseAsyncClientBuilder.java:22)
    at software.amazon.awssdk.core.client.builder.SdkDefaultClientBuilder.build(SdkDefaultClientBuilder.java:129)
    at com.crowdblink.software.eventrepo.container.factory.KinesisFirehoseClientFactory.<clinit>(KinesisFirehoseClientFactory.java:42)
    at com.xxxx.software.eventrepo.container.EventsApiLambdaHandler.sendAsyncBackup(EventsApiLambdaHandler.java:246)
    at com.xxxx.software.eventrepo.container.EventsApiLambdaHandler.lambda$backupPostAndPatch$2(EventsApiLambdaHandler.java:220)
    at java.base/java.util.concurrent.CompletableFuture.biApply(Unknown Source)
    at java.base/java.util.concurrent.CompletableFuture$BiApply.tryFire(Unknown Source)
    at java.base/java.util.concurrent.CompletableFuture.postComplete(Unknown Source)
    at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(Unknown Source)
    at java.base/java.lang.Thread.run(Unknown Source)

Any ideas?





Delegate DynamicInvoke vs MethodInfo invoke?

I recently saw that you can convert a MethodInfo into a Delegate. But sometimes you may not know what exactly its params or type is. So thats where Delegate.DynamicInvoke comes into play.

But whats the difference between those two ? Which is faster and which produces less GC alloc calls ?





C# reflection: how to get the item type of a List? [duplicate]

Suppose I have a "Type mytype", and if I do "mytype.ToString()", I get "System.Collections.Generic.List`1[Example1.Employee]", how do I get the list item type, which is "Example1.Employee"? Do I have to parse this string to get this list item type? Is there a more elegant way, such as "mytype.ItemType"?

Also, why is there a "`1" appendix at the end of "System.Collections.Generic.List`1"?

And, why is there a "`2" at the end of "System.Collections.Generic.Dictionary`2"?





mardi 30 mars 2021

Getting the class name of the super class?

I am writing some code to check the structure of other people's code.

Lets say ClassB extends ClassA

I know I can do

Class clazz = Class.forName("classB");
clazz.getSuperclass();
clazz.getName(); //ClassA

but I dont want to do it this way because it requires my jvm return the actual class of ClassA (which is not in the classpath)

currently I am using

Class clazz = Class.forName("classB", false, classLoader);

to not initialize the class, so that I dont have to put so many irrelevant jars into my classpath.

Is there a way I can get the Super's classname from ClassB without requiring me to include ClassA's jar in the classpath?





DynamicMethod pass objects to method

The problem

I need to generate a fast reflection based method during runtime. Therefore i looked into dynamic methods. The problem is im stuck with my limited knowledge.

Thats the method i need to call with a dynamic method.


public struct EntityManager{

    public void SetComponent<T>(Entity e, T component) where T : struct, IComponentData{
       // Simplified
    }
}

// The component to pass in it
public struct ComponentExample : IComponentData{}

And im stuck with the part where i need to pass the Entity and the Component into the method. I just cant find any example on how we do that.

var dm = new DynamicMethod(
    "SetComponent",       
    typeof(void),  
    new [] { typeof(Entity), typeof(ComponentExample)}, 
    false
);             

var il = dm.GetILGenerator();
// Emit Entity & the ComponentExample ???
il.EmitCall(OpCodes.Call, genericMethod, null);
il.Emit(OpCodes.Ret);

The question

How exactly do we "emit" an struct ( Entity ) and an object into the DynamicMethod for executing it ? Glad for any help on this topic !





Checking if a Python function referenced anything out-of-scope

I'm exploring what's possible to do in Python and recently came across this question: after running a function, is it possible to programmatically determine whether it has referenced anything out-of-scope? For example:

import module1

y = 1

def foo1(x):
    return y + x  # yes - it has referenced 'y' which is out of foo1 scope

def foo2(x):
    return module1.function1(x)  # yes - it has referenced 'module1' which is out of foo2 scope

def foo3(x):
    return x*x  # no - it has only referenced 'x' which is an input to foo3, so the code executed within the scope of foo3

Are there some reflection / analysis tools for this? Maybe this could be achieved with the 'trace' module somehow?





lundi 29 mars 2021

In Python, how to instantiate a class by its name instead of referencing it directly? [duplicate]

In order to avoid a circular reference, I'd like to reference a class by it's name instead of directly.

For example:

class A:
    x: str = 'nice'

# how can I get this reference by using the name and package of A instead of referencing it directly?
myclass = A

a1 = myclass()

# a1 is an instance of A as expected

print(a1)
>>> <__main__.A object at 0x7f82b86b6eb0>

I'm looking for something like get_class('A') which returns a reference to A. I'm on Python 3.8.5

I'm a new to Python reflection - is there a built in way to do this?

Thanks!





dimanche 28 mars 2021

Creating array class in java [duplicate]

I am looking for a function that takes a type and returns a class representing arrays of objects of that type. For instance, if we name the function "getArrayClass", the following should be true:

getArrayClass(String.class) == String[].class == class [Ljava.lang.String

How can I create a function that does this, or does one already exist?

The following function would return a Type representing the appropriate array, but what I really need is a Class.

Type getArrayType(Type componentType) {
    return new GenericArrayType() {
        public Type getGenericComponentType() {
            return componentType;
        }
    };
}




Java store reflected Method statically in class: Safe?

Is something like the following 'safe' in Java, and why?

public final class Utility {

    private Utility() {}

    private static Method sFooMethod = null;

    public static void callFoo(SomeThing thing) {
        try {
            if(sFooMethod == null)
                sFooMethod = SomeThing.class.getMethod("foo");
            sFooMethod.invoke(thing);
        } catch(Exception e) {}  // Just for simplicity here
    }

}

My rationale would be that even if another thread writes to sFooMethod in the background and the current thread sees it suddenly somewhere during execution of callFoo(), it would still just result in the same old reflective invoke of thing.foo()?

Extra question: In what ways does the following approach differ (positive/negative) from the above? Would it be preferred?

public final class Utility {

    private Utility() {}

    private static final Method sFooMethod;
    static {
        try {
            sFooMethod = SomeThing.class.getMethod("foo");
        } catch(Exception e) {}
    }

    public static void callFoo(SomeThing thing) {
        try {
            if(sFooMethod != null)
                sFooMethod.invoke(thing);
        } catch(Exception e) {}
    }

}




vendredi 26 mars 2021

Why is this foreach loop missing a property from the class?

I'm basically trying to use reflection to flatten any class into a dictionary so that I can generically use and bind them in Blazor. I then need to be able to create an instance of the class and populate it with the data from the dictionary (which will have been updated by a component).

e.g

public class Order
{
    public Guid Id { get; set; }
    public Customer Customer { get; set; }
    public string Address { get; set; }
    public string Postcode { get; set; }
    public List<string> Test { get; set; }
    public List<Test> Test2 { get; set; }
}

public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName => $"{FirstName} {LastName}";
    public Gender Gender { get; set; }
    public List<string> Test { get; set; }
}

Should become:

{
  "Id": "",
  "Customer.FirstName": "",
  "Customer.LastName": "",
  "Customer.Gender": "",
  "Customer.Test": "",
  "Address": "",
  "Postcode": "",
  "Test": "",
  "Test2": ""
}

For some reason when I iterate the properties of the Order class, Test2 is missed. The loop shows the property in the collection when I put a breakpoint, it just seems to skip it. I've never seen this happen before.

Code: https://dotnetfiddle.net/g1qyVQ

I also don't think the current code with handle further nested depth which I would like it to be able to work with any POCO object really.

Also if anyone knows a better way to do what I'm trying, I would love to find an easier way. Thanks





How to get ResourceManager from AttachedProperty

I want to get ResourceManager with the help of an AttachedProperty from the user Consider the following code:

<window:

xmlns=res="clr-namespace:WpfApp11.ResourceFolder"
myAttach.ResourceName="res.Strings.resx"
/>

Now I want res.Strings.resx to become ResourceManager

public OnResourceNameChanged(...)
{
   ResourceManager res = GetResourceManager("res.Strings.resx");
   res.GetObject(key);
}

How should this be done?





jeudi 25 mars 2021

Getting value of a generic inherited private field

I'm having some trouble trying to access private fields from an inherited generic class. It throws me an exception with the object owner I'm using to try to get the value, but if I use that same owner to get the field from a field directly declared with that generic type it works fine.

Here's my fields:

public class Bool : DebugProperty<bool>
{
    ...
}

DebugProperty<bool> m_nonIngeriteedBool;
Bool m_inheritedBool;

Here's how I get the value from m_nonIngeriteedBool field:

FieldInfo field = owner.GetType().GetField(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);

Type type = field.FieldType;

FieldInfo m_value = type.GetField("m_value", BindingFlags.Instance | BindingFlags.NonPublic);

object val = m_value.GetValue(field.GetValue(owner)).ToString();

This works fine and returns the proper value, but for m_inheritedBool I can't find how to make it work. Here's what I currently have:

FieldInfo field = owner.GetType().GetField(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);

Type type = field.FieldType;

while (type != typeof(DebugProperty<>))
{
    type = type.BaseType;

    if (type.IsGenericType)
        type = type.GetGenericTypeDefinition();
    
    if (type == null)
        break;
}

FieldInfo m_value = type.GetField("m_value", BindingFlags.Instance | BindingFlags.NonPublic);

object val = m_value.GetValue(field.GetValue(owner)).ToString();

This returns the proper m_value field, but when trying to get the value fails throwing the following error:

System.ArgumentException: Field m_value defined on type DebugProperty`1[T] is not a field on the target object which is of type Test+Bool.
Parameter name: obj

What object should I use to return the correct value?





Access class decorator argument using reflect-metadata

Consider a class decorator with one argument:

@TableName("Orders")
export class Order {
 // ...
}

And the decorator defined as:

import "reflect-metadata";

const classDecoratorKey = Symbol.for("custom:TableName");

export function TableName(tableName: string): ClassDecorator {
  return (constructor: Function) => {
    Reflect.defineMetadata(classDecoratorKey, tableName, constructor);
  }
}

export function getTableName(target: any): string {
  return Reflect.getMetadata(classDecoratorKey, target.constructor, "class") || "";
}

I expect now to get the @TableName value "Orders". How can I retrieve the class decorator's argument value?

let order = new Order();
getTableName(order); // "" but expected "Orders"




React Storybook - Button pointing to story

I want to create a button to put inside my components where I can link the related story in Storybook. This is not a hard task, but it's very time-consuming linking each story for each component.

Now my solution is this

export default function StorybookBadge({path, story = "plain"} : IShowInStorybookProps){

    const openStorybook = () =>{
        const storybookUrl = process.env.REACT_APP_STORYBOOK_URL || "http://localhost:6006"
        window.open(`${storybookUrl}?path=/story/${path.replaceAll("/", "-").toLowerCase()}--${story}`)
    }

    return <div className='show-in-storybook' onClick={openStorybook}>
        <img src={SVGLogo} />
    </div>
}

and my folder structure is this

enter image description here

So in ActivateAccount I would write

export default function ActivateAccount(props){

    return <div>
        <StorybookBadge path='Components/ActivateAccount' />
    </div>
}

My question is: is there a way to catch the index.stories.tsx and grab the path with some reflection?





mercredi 24 mars 2021

how to update a map value by reflection ( params is interface )

Encountered such a problem, expect to make a general method to update the value in the map, as in the above example:


type Student struct {
    Name string `json:"name"`
}

func TestReflect(t *testing.T) {
    a := make(map[int]Student)
    update(&a)
    fmt.Println("outer:",a)
}

func update(a interface{}) {
    b := copyStruct(a)
    valueStr := "{\"0\":{\"name\":\"test\"}}"
    _ = json.Unmarshal([]byte(valueStr), &b)
    fmt.Println("inner:",b)
    a = b
}

func copyStruct(a interface{}) interface{} {
    // Create a pointer type to the underlying element type
    return reflect.New(reflect.TypeOf(a).Elem())
}

The expected output result is: inner: map[0:map[name:test]] outer: map[0:map[name:test]]

But the actual output is : inner: map[0:map[name:test]] outer: map[]

How can i do .... Can somebody help





Iterate Over Struct in Go and Identify / Do Type Assertion on Fields

I am attempting to iterate over a struct which looks like this:

type Cpe23 struct {
    Part      string
    Vendor    string
    Product   string
    Version   Version
    Update    string
    Edition   string
    SwEdition string
    TargetSw  string
    TargetHw  string
    Language  string
    Other     string
}

All I am looking to do is concatenate the values into a string and print the results. The issue comes from the fact that the Version struct is obviously not a string, so it needs to be treated differently. Here is the Version struct:

type Version struct {
    Original string
    Semver   *semver.Version
    Valid    bool
}

In the case of the Version field, I want to pull out the Original value and add that to the resulting string. Here is the code that I have tried based on what I was able to google. I know I am close but I just can't quite seem to figure out reflection/type assertion...

func FormCpeString(component Cpe23) string {
    cpeString := "cpe:2.3"
    v := reflect.ValueOf(component)
    for i := 0; i < v.NumField(); i++ {
        f := v.Field(i)
        // If an empty field, replace with asterisk (all)
        if f.Interface() == "" {
            cpeString += ":*"
        } else if f.Type().Name() == "Version"{
            t := f.(Version)
            cpeString += fmt.Sprintf(":%s", t.Original)

        } else {
            // do some validation checks here TODO
            cpeString += fmt.Sprintf(":%s", v.Field(i).Interface())
        }
    }
    return cpeString
}

The error I am getting is ./main.go:433:10: invalid type assertion: f.(Version) (non-interface type reflect.Value on left)

I understand what this error is saying, I just can't seem to find the right syntax to allow me to pull fields out of the Version. Any guidance would be appreciated.





Swift - How could I iterate over all possibilities of a collection of stridable variables

I have a configuration defined with various ranges and would like to iterate over all the possibilities without coding it explicitly.

My guess is to use reflection but perhaps there is an easier way?

here is an example:

struct Settings {
    var a = stride(from: 0, to: 24, by: 1)
    var b =  stride(from: 0, to: 4, by: 1)
    var c = stride(from: 0, to: 10, by: 2)
    var d = stride(from: 0, to: 10, by: 2)
    var e = stride(from: 0.0, to: 0.5, by: 0.05)
    var f = stride(from: 0, to: 10, by: 1)
}

I want to avoid nested loops if possible. i..e this isn't great:

let settings = Settings()
for v1 in settings.a {
 for v2 in settings.b {
  for v3 in settings.c {
   ...
    ...
    }
   }
  }
 }
}


would love to have something similar to CaseIterable which could provide all of the combinations





mardi 23 mars 2021

Switching classes and functions dynamically based on string values from tables

Hi I have got a requirement to extract various reports from our project management system into tables. Around 28 reports.

So initially I thought about extracting it in different blocks based on the report IDs like this

                        switch (reportId)
                        {
                            
                            case 737://project static
                                
                                
                                KipReport<ApiProjectStatic> rptPS = JsonConvert.DeserializeObject<KipReport<ApiProjectStatic>>(responseBody,dateTimeConverter);
                                List<ApiProjectStatic> jsonPS = (List<ApiProjectStatic>)rptPS.Data;
                                //jsonPS = JsonConvert.DeserializeObject<List<ProjectStaticMain>>(rpt.Data);
                                List<KipProjectStatic> PM = new List<KipProjectStatic>();
                                PM = _mapper.Map<List<KipProjectStatic>>(jsonPS);
                                PM.Select(p => { p.LogId = log.LogId; return p; }).ToList();
                                _context.KipProjectStatics.AddRange(PM);
                                _context.SaveChanges();
                                if (rptPS.TotalPages > 1 && rptPS.PageNumber != rptPS.TotalPages)
                                {
                                    GetKeyedinReport(reportId, rptPS.PageNumber + 1,log);
                                }
                                break;
                            case 740:
                                 .....
                                 .....

For every reports what changes here is the classnames and Context objects. So my question is, is there any way to switch those classes from string names coming from tables

For example I have a table like this

Report ID     ReportName                ModelClass          JSONClass            Context
--------------------------------------------------------------------------------------------------
737           Project Details         KipProjectStatic      ApiProjectStatic     KipProjectStatics
738           Program rreport         KipProgramme          ApiProgramme         KipProgrammes
.....
...
.
---------------------------------------------------------------------------------------------------

So we are looping through these data and switches the functions and classes based on the string values coming from different columns. Hope its clear

Also here GetKeyedinReport function is always the same for all reports.. It just returns the json based on the ID we pass

Please share a solution





Is there a C# function to print the function instructions as String using reflection?

I would like to print the content of my Function as String, and I have tried different reflection methods and also a lib I found on GitHub, However, what it does is to print the instructions in IL code. Also, I'd like to mention that I have a lambda code, so that, it is printing instructions with the label lambda instead of the instructions I need to. It does make sense. This solution is based on the IL code created for running in the machine, but I need the version of the class document. This is for an automated tool to look for different places in the code using lambda expressions with a specific function.

I have tried the following but the result is not expected:

In addition, as a different approach, I tried to get the classpath to use the ReadLines C# function in order to read all lines and look for my target function, but, this is returning the assembly path but I cannot use ReadLines since the assembly is not a document text.

I need to do something like the following:

using System;
class Foo 
{
  public List<Item> SetItems() 
  {
      List<Item> items = new List<Item>();
      return new List<SomeType>(items).ForEach(
        i => AssignNewType(i)
      ).FindAll(i=> i.type == SomeType.newType);
  }
}

Another class:

ClassReader.Print(Foo, "SetItems");

Expected Result as String:

Function content: List<Item> items = new List<Item>(); return new List<SomeType>(items).ForEach( i => AssignNewType(i)).FindAll(i=> i.type == SomeType.newType);

Thanks for your help!





Invoke MethodInfo with void* as a parameter

The problem

Theres an internal method i need to invoke via reflection. It looks like this...

internal void SetComponentDataRaw(Entity entity, int typeIndex, void* data, int size)

Obtaining the MethodInfo is no problem, but calling it is one. I need to pass a void pointer to it, but such a void pointer can NOT be cast to an object. When i box that pointer, i receive an error later on that tells me it can not unbox it properly.


var SetComponentDataRawInfo = typeof(...).GetMethod("SetComponentDataRaw", ...);
var entity = someEntityToPass;
var cmp = new StructToPassToTheMethodAsAPointer();

// My first attempt, not possible to cast
unsafe {
   var handle = GCHandle.Alloc(cmp, GCHandleType.Pinned);
   var adress = handle.AddrOfPinnedObject();
   var ptr = adress.ToPointer();
   var sizeOfComponent = UnsafeUtility.SizeOf(type);

   var parameters = new [] {entity, cmpType.TypeIndex, (object)ptr, sizeOfComponent}; // (object)ptr not possible
   SetComponentDataRawInfo.Invoke(em, parameters);
   handle.Free();
}


// Second attempt
unsafe {
   var handle = GCHandle.Alloc(cmp, GCHandleType.Pinned);
   var adress = handle.AddrOfPinnedObject();
   var ptr = adress.ToPointer();
   var sizeOfComponent = UnsafeUtility.SizeOf(type);

   var parameters = new [] {entity, cmpType.TypeIndex, Pointer.Box(ptr, typeof(void*)), sizeOfComponent};
   SetComponentDataRawInfo.Invoke(em, parameters);
   handle.Free();
}

The second attempt is able to invoke the method... but i receive the following exception : ArgumentException: Object of type 'System.Reflection.Pointer' cannot be converted to type 'System.Void*'.

The question

How do we invoke a MethodInfo with a pure void* as an parameter ? Glad for any help on this topic !





lundi 22 mars 2021

create a new struct variable with reflect and keeping the struct tags

I'm having problems when trying to clone a struct with reflect.New and later marshaling to json, the result is not showing the json field names.

Here is a simplified version


type Person struct {
    Id        int     `json:"personid"`
    LastName  string  `json:"lastname"`
    FirstName string  `json:"firstname,omitempty"`
    Title     string  `json:"title"`
}


stmt := "select firstname,lastname from t_person"

rows := GetResults(db, stmt, Person{})

j, _ := json.Marshal(&rows)
log.Printf("persons: %s", j)



func GetResults(db *sql.DB, stmt string, p interface{}) []interface{} {

    rows, err := db.Query(stmt)
    if err != nil {
        log.Fatal(err)
    }

    t := reflect.TypeOf(p)

    var rs []interface{}
    for rows.Next() {
        // create new var
        n := reflect.New(t).Elem()

        pointers := make([]interface{}, 2)
        pointers[0] = n.Field(1).Addr().Interface()
        pointers[1] = n.Field(2).Addr().Interface()

        err := rows.Scan(pointers...)
        if err != nil {
            log.Fatal(err)
        }
        rs = append(rs, pointers)
    }

    return rs
}

I expected something like this ..

[ {"lastname":"don","firstname":"joe"}, {"lastname":"mary","firstname":"joe"} ... ]

but got

 [["don","joe"],["mary","joe"],["peter","pan"],["super","man"]]

any help will be appreciated





Kotlin Reflection : How to add a KFunction to a list via reflection?

I want to add to a MutableList<(some-type)->Uint> at run-time depending on the type. I mostly got it, but I can't figure out how to get the instance info into the KFunction I have.

This code is a bit contrived, but it's a stripped down example of what I'm trying to do. I'm trying to get rid of a bunch of boiler plate code by wiring up dispatch at runtime.

This code compiles, but blows up at runtime when using the lists with the error : java.lang.IllegalArgumentException: Callable expects 2 arguments, but 1 were provided. from the doSomeWork() when dispatching.

This error makes me think the instance isn't associated w/ the KFunction I'm adding to the list... but I don't know how to associate it. I have the instance handy, I just don't know how to attach it. Or maybe it's something else entirely.

The code :

package reflectwork

import kotlin.reflect.KFunction
import kotlin.reflect.full.functions
import kotlin.reflect.full.hasAnnotation
import kotlin.reflect.full.memberProperties

interface Marker

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class WireMeUp

class Dispacher {
    val strList = mutableListOf<(String)->Unit>()
    val intList = mutableListOf<(Int)->Unit>()
    val floatList = mutableListOf<(Float)->Unit>()

    fun doSomeWork() {
        strList.forEach { it("Some work") }
        intList.forEach { it(57) }
        floatList.forEach { it(3.14f) }
    }
}


class Client : Marker {
    @WireMeUp fun doStringWork(str:String) { println(str) }
    @WireMeUp fun doIntWork(i:Int) { println(i) }
    @WireMeUp fun doFloatWork(f:Float) { println(f) }
}


fun wire(app:Marker, dis:Dispacher) {

    app::class.functions.forEach { func ->
        if( func.hasAnnotation<WireMeUp>() ) {
            require( func.parameters.size == 2 )
            val parmType = func.parameters[1].type

            dis::class.memberProperties.forEach{ prop ->
                if( prop.returnType.arguments.size == 1 ) {

                    val argType = prop.returnType.arguments[0].type
                    // I have no idea how to compare a [type] to a ([type]) -> Unit
                    // so just do it via strings. better way?
                    if( "($parmType)->kotlin.Unit" == argType.toString().replace(" ","")) {

                        println("found match, setting type = $parmType")
                        // get the list. No idea how cast to the correct type
                        // which in theory I know at this point.
                        val lst = prop.call(dis) as MutableList<KFunction<*>>

                        // this works, but blows up at runtime in doSomeWork()
                        // with the error :
                        // java.lang.IllegalArgumentException: Callable expects 2 arguments, but 1 were provided.
                        // I think because "func" has not instance? Not sure how to attach an instance... which I have
                        lst.add( func )

                    }
                }
            }

        }
    }
}


fun main() {

    val dispatch = Dispacher()
    val cli = Client()
    wire(cli,dispatch)
    dispatch.doSomeWork()
}

Any advice?

Thanks in advance.





How to map string literals to types in C++

I'm writing a small 2D game and I'm currently adding scripting capabilities to it (using Lua or Python), and I stumbled on this problem (which I think will lead me to implement some kind of reflection system for my game):

I'm using the Entity Component System pattern, and the definition for an entity is provided by a script (a Lua table or a Python dict), so whenever I want to construct an entity I run the script:

player = {
     transformComponent = { 
            position = {1.0, 2.0, 0.0},
            scale = {1.0, 2.0, 1.0}
     },
     spriteComponent = {
            fileName = 'imageFile.png',
            numRows = 4,
            numCols = 6
     }
}

and so on. In an EntityFactory I have a map of EntityFactoryFunctions, keyed by the name of the entity (e.g. 'Player'), and I call them when I need to construct such named entity.

Now, each factory function will read the table (dict) of the entity and get all the names of the components it needs to add to the entity.

Entity *CreateEntity(const std::string entityType) // table / dictionary name in script
{
    Entity *newEntity = Scene::GetInstance().AddEntity();
        
    return mEntityFactories[entityType](newEntity);
}

typedef Entity *(*EntityFactoryFunction)(Entity*);
std::map<std::string, EntityFactoryFunction> mEntityFactories;

Problem is, my ECS uses a function of the type enity.AddComponent<COMPONENT_TYPE>():

Entity *PlayerFactory(Entity *entity)
{
    // read components from Lua table / Python dictionary
    // get strings of components' names and store them into vector
    Vector<std::string> componentNames;

    // create components and add to entity
    for (const auto &componentName : componentNames)
    {
        Component *component = mComponentFactories[componentName](/* pass a reference to component table / dictionary */);
        entity->AddComponent<......>(component);  // I must know the component type
    }

    return entity;
}

How can I get the name of the component to pass to the function template? Do I need some kind of reflection system?





Can MethodInfo safely be used for dictionary keys?

I'm trying to use MethodInfo instances as dictionary keys but I am not able to verify that this is well supported by the .net runtime.

To be more precise, given two RuntimeMethodInfo instances m1 & m2 that were obtained from the .net reflection API and are representing the same method. Does the .net runtime always guarantees m1.GetHashCode() == m2.GetHashCode() and m1.Equals(m2) ?

I could find the same question on stackoverflow : Can MethodInfo be used as Dictionary key?

The answer claims that, yes, MethodInfo can be used for dictionary keys. However I was unable to verify this claim.

Looking at the source code of RuntimeMethodInfo, it appears that the implementation of GetHashCode() simply calls the default implementation of RuntimeHelpers.GetHashCode() (when the method is not generic).

If my understanding is correct RuntimeHelpers.GetHashCode(), is only guaranteed to return identical hash codes when objects references are the same.

If my assumption is correct, this would mean that MethodInfo cannot safely be used as a dictionary key unless the reflection API is always guaranteed to return the same MethodInfo instance for the same given method. Is this actually the case ?

Does anybody have more information on this subject ? Thank you !





dimanche 21 mars 2021

What type does nameof operator take in c#

I'm writing some editor UI code in Unity and am calling nameof() frequently to get string representations of relative property paths from the object I am editing.

my code currently looks like this

EditorGUI.PropertyField( // draw UI
     new Rect(rect.x+ currentOffset, rect.y, 110, EditorGUIUtility.singleLineHeight), // positioning
     element.FindPropertyRelative(nameof(LogicalFuzzyRule.predicate1.input)), // **get the property**
     GUIContent.none // nothing else
     );  


EditorGUI.PropertyField(
     new Rect(rect.x+ currentOffset + 110, rect.y, 60, EditorGUIUtility.singleLineHeight),
     element.FindPropertyRelative(nameof(LogicalFuzzyRule.predicate1.isOrIsNot)),
     GUIContent.none
     ); 

EditorGUI.PropertyField(
    new Rect(rect.x+ currentOffset + 170, rect.y, 40, EditorGUIUtility.singleLineHeight),
    element.FindPropertyRelative(nameof(LogicalFuzzyRule.predicate1.state)),
    GUIContent.none
    );

I would really like to be able to refactor this to pass in the start of the path like

var predicate = LogicalFuzzyRule.predicate1;

EditorGUI.PropertyField( // draw UI
     new Rect(rect.x+ currentOffset, rect.y, 110, EditorGUIUtility.singleLineHeight), // positioning
     element.FindPropertyRelative(nameof(predicate.input)), // **get the property**
     GUIContent.none // nothing else
     );  

and pass in the value of predicate via a function. Is this possible at all? does it even make sense to break up this call?

The code I would like to write does not compile of course, what type would the rhs of the 'predicate' assignment need to be in order for this to work?





Java Reflections Library - Class loader warnings about unrelated classes

I'm using the Reflections library to get all classes annotated by a specific annotation in a specific package.

IndexSpec annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IndexSpec {
    String value();
}

Annotated class

@IndexSpec("connected_clients")
public class ConnectedClients implements ElasticIndex {
    [...]
}

Reflection

[...]

var reflections = new Reflections(new ConfigurationBuilder()
        .setUrls(ClasspathHelper.forPackage("a.b.c.indices")) // Package name redacted for legal reasons
        .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));

var annotatedIndices = reflections.getTypesAnnotatedWith(IndexSpec.class);

[...]

This code works fine but I get a large amount of warnings. There is are a few hundred of them for many of different, unrelated classes.

Reflections says it found a lot of classes in a package that contains exactly two classes.

Reflections took 2303 ms to scan 1 urls, producing 2898 keys and 11715 values

The warnings all look like this:

[org.reflections.Reflections] could not get type for name com.fasterxml.jackson.databind.ObjectMapper from any class loader

Why is the library scanning classes in a different package than what it was configured for?





C# how use reflection to load dependency assembly?

I am using reflection to load Assembly1.dll and print out all its methods:

            Assembly assembly1 = Assembly.LoadFile("c:\temp\Assembly1.dll");

            foreach (Type type in assembly1.GetExportedTypes())
            {
                Console.WriteLine();
                Console.WriteLine(type.ToString());

                foreach (MethodInfo methodInfo in type.GetMethods())
                {
                    Console.Write($"    {(methodInfo.IsStatic ? "static" : "")} {methodInfo.ReturnType} {methodInfo.Name} (");
                    ParameterInfo[] aParams = methodInfo.GetParameters();

                    for (int i = 0; i < aParams.Length; i++)
                    {
                        ParameterInfo param = aParams[i];

                        if (i > 0)
                            Console.Write(", ");

                        Console.Write($"{ (param.ParameterType.IsByRef && param.IsOut ? "out" : "") } { (param.ParameterType.IsByRef && !param.IsOut ? "ref" : "") } {param.Name}");
                    }
                }
            }

When the last "Consol.Write" runs, it threw the following exception:

System.IO.FileNotFoundException: 'Could not load file or assembly 'Assembly2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.'

I know why, because some of the methods in Assembly1.dll has some parameters, and the types of these parameters are defined in Assembly2.dll.

So, how do I solve this problem? I mean, how do I load both assemblies?





samedi 20 mars 2021

PHP/Laravel - Define function for another class

is there any way to define a function for a specific class/object outside of it?
I made an example using PHP 8 functionalities:

// Call this function somewhere
public function registerFunctions() {

    Magic::createFunction(
        target: A::class,
        visibility: 'public',
        name: 'foo',
        parameters: ['object' => Object::class, 'text' => 'string'],

        closure: function(Object $object, string $text) {
            echo 'This is my class which exists on runtime only: ' . $params['text'];
        }
    );

}

Magic::createFunction will produce an internal function (not visible for humans) like this:

class A {
    
    public function foo(Object $object, string $text) {
         $object->setText($text);
         echo 'Set text to object: ' . $text;
    }
    
}

So I can use:

(new AB())->foo(myObject, 'Hello world!'); // variable "text" in "myObject" was set to 'Hello world.'

I know there'e something like magic methods in PHP, but I have to define them manually inside of t's class. I want to create them out of their class. Could this be done using Reflection or similar tools?

Thanks in advance!





vendredi 19 mars 2021

kotlin-reflect library importing issues

I'm following udacity kotlin bootcamp lectures. I'm working on annotations & reflections part. However, I face the compile errors as shown on the screenshot. No problem till import kotlin.reflect.full but I can't use any of the extension functions provided by kotlin-reflect library.

I'm very new to kotlin and android, so I know my question might be very basic and sound dumb.. but any help will be appreciated to me, a super-newbie, to start this kotlin journey :D Thanks!

kotlin.reflect.full importing issues





IServiceProvider resolve dynamic type

I am trying to resolve a service in a dynamic way. I have a bunch of model classes and for each a custom geneator class. Now if I add new models I have to add a generator for this type, which is quiet okay, because every models has other properties and needs to be generated in a different way. My problem here is, that I have an abstract generated which generates the model by it's input. Here's an example:

    // The following classes and interfaces are just examples 
    public interface IGenerator<T> where T : IModel
    {
        T Generate(string someInput);
    }

    public class Model_1_Generator : IGenerator<Model1>
    {
        Model_1 Generate(string someInput){ ... }
    }

    public interface IModel
    {
    }

    public class Model_1 : IModel
    {
    }


    private IModel GenerateModel(Type modelType, string someInput)
        {
            if (modelType == typeof(Model_1))
            {
                return _model_1_Generator.Generate(someInput);
            }

            if (modelType == typeof(Model_2))
            {
                return _model_2_Generator.Generate(someInput);
            }

            if (modelType == typeof(Model_3))
            {
                return _model_3_Generator.Generate(someInput);
            }

            throw new NotImplementedException($"Type {modelType} is not implemented yet");
        }

Note: I changed the names of the services and models to make it more understandable

This way I have to extend the method GenerateModel(Type) every time I add new Model types. Now I want to "simplify" this by dynamically resolving the generator by the given type:


    private readonly IServiceProvider _services;

    private IModel GenerateModel(Type modelType)
        {
            // This is the problematic line
            var generator = _services.GetService<IGenerator<modelType>>();

            return generator.Generate();
        }

The problem is, that I cannot resolve the services because the type is a variable. Is there a way to resolve the service by a given type





Filter GetTypes() to remove extra type created from partial class with async method [duplicate]

If I have a partial class like this:

    public partial class ExampleClass { }
    public partial class ExampleClass
    {
        public async Task ValidateAsync() =>
            await Task.Delay(1000);
    }

and I run GetTypes() on its assembly:

    Type asmType = typeof(ExampleClass);
    Assembly asm = asmType.Assembly;
    List<Type> m1 = asm.GetTypes();

I get two types for ExampleClass, one normal one and an extra one with name suffix related to ValidateAsync.

This extra type is a pain because in Release builds it is optimised to a struct (class in Debug builds) and I want to filter it out.

What is the best way to do this?





jeudi 18 mars 2021

Is there a way to set a generic type to a Blazor component at runtime?

<GenericInputFor> provides markup based on the argument it receives and its type, it behaves fine with compile time types, but when I try to iterate through some class properties with reflection it says that the type cannot be inferred :

 @foreach (var property in typeof(SomeClass).GetProperties())
        {
           <GenericInputFor Model="property.GetValue(in2,null)" ModelChanged="@((ChangeEventArgs __e) => property.SetValue(in2, __e.Value))"></GenericInputFor>
        }

@code {
    public SomeClass in2 { get; set; }

    protected override void OnInitialized()
    {
        in2 = new SomeClass();
        base.OnInitialized();
    }
}

I have seen multiple awesome solutions like Setting generic type at runtime and Creating a Generic type instance with a variable containing the Type but I couldn't apply it to blazor components.





List

I have List like below code snippet:

List<String> nameList = new ArrayList<>();
nameList.add("Robert");
nameList.add("Tom");
nameList.add("Curran");
//robert, tom, curran

Now I want to modify these list values using reflection API in Java. Output something like below we print list:

//xxx,xxx,xxx





Getting warnings when I am starting my Springboot application : WARNING: An illegal reflective access operation has occurred

Here is the warning :

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.vmplugin.v7.Java7$1 
         (file:/C:/Users/.m2/repository/org/codehaus/groovy/groovy/2.5.6/groovy-2.5.6.jar) to 
         constructor java.lang.invoke.MethodHandles$Lookup(java.lang.Class,int)
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.vmplugin.v7.Java7$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

What may be causing this and how to get rid of them?





Benchmark on Create Instance with AOT

What is the performance of difference ways of Instance Creation between Mono and IL2CPP?

  1. Direct Create Instance
  2. Compile Expression, then DynamicInvoke
  3. Compile Expression<Func<object[], object>>, then cast to Func<object[], object>, then Invoke
  4. Compile Expression, the cast to Func then Invoke directly (not suitable for parameter constructor)
  5. ConstructorInfo.Invoke
  6. cached ConstructorInfo, then Invoke
  7. Activator.CreateInstance




On Java, using reflect, how to tell whether a field's value is set on declaration or within a constructor body

I'm trying to tell whether a a field's value in a Java class is set on declaration or within a constructor body.

Consider the following code for Case Declaration:

class MyClass {
    int myField = 42;   // myField is initialized on declaration
    MyClass() {
        // this constructor is **not** setting myField
    }
}

versus Case Constructor:

class MyClass {
    int myField;      // myField is initialized on declaration with base value (0)
    MyClass() {
        myField = 42; // myField gets value on constructor
    }
}

Rephrasing my question: by using reflection can I tell whether I'm on Case Declaration or on Case Constructor, and if so, how?

The closest I've got is getting the field value from an instance (for example on this question) But that requires instantiation, so I finally get the value 42 in both cases.

The code for that could be something like:

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    Field field = MyClass.class.getDeclaredField("myField");
    MyClass instance = new MyClass();
    System.out.println("myField: " + field.get(instance));  // it writes 42 in both cases
}

I could parse both classes' source code but that would require adding some complexities to the workflow I'd rather avoid.

In case you want some context, I'm teaching an introductory course on OOP using Java, and I provide my students some JUnit code to check whether their solutions meet the requirements. In this concrete case I'm trying to force them to start using constructor's initialization for their first time.





How do I get information about function calls from a Lua script?

I have a script written in Lua 5.1 that imports third-party module and calls some functions from it. I would like to get a list of function calls from a module with their arguments (when they are known before execution).

So, I need to write another script which takes the source code of my first script, parses it, and extracts information from its code.

Consider the minimal example.

I have the following module:

local mod = {}

function mod.foo(a, ...)
    print(a, ...)
end

return mod

And the following driver code:

local M = require "mod"
M.foo('a', 1)
M.foo('b')

What is the better way to retrieve the data with the "use" occurrences of the M.foo function?

Ideally, I would like to get the information with the name of the function being called and the values of its arguments. From the example code above, it would be enough to get the mapping like this: {'foo': [('a', 1), ('b')]}.

I'm not sure if Lua has functions for reflection to retrieve this information. So probably I'll need to use one of the existing parsers for Lua to get the complete AST and find the function calls I'm interested in.

Any other suggestions?





Function as parameter in async method

I call a method containing a function:

public void DoMagicStuff(Func<T> anyfunction) {
  // do lots of magic stuff
}

This works:

public void DoNonAsyncStuff() {
  DoMagicStuff(()=> {
     AnotherFunction();
  }
}

While this does not:

public async Task<CustomClass> DoAsynStuff() {
   DoMagicStuff(()=> {
     return await DoSomethingDifferent();
  }
}

"The await operator can only be used in async functions"

How do I make this work for async methods?





mercredi 17 mars 2021

How to reflection check nullable object is IDictionary

How to reflection check nullable object is IDictionary

e.g :

if object is not null it can use is keyword to check.

void Main()
{
    Dictionary<string, object> v = new Dictionary<string,object>();
    Console.WriteLine(CheckValueIsIDictionary(v)); //true
}

bool CheckValueIsIDictionary(object value){
    return value is IDictionary;
}

but if parameter value is null then will get false

void Main()
{
    Dictionary<string, object> v = null;
    Console.WriteLine(CheckValueIsIDictionary(v)); //false
}

bool CheckValueIsIDictionary(object value){
    return value is IDictionary;
}

I expect get true result, thanks!


update:

I want to check value declare type is a IDictionary

before example you can know this null value is from Dictionary<string,object> and this type is a IDictionary and I want to get the relationship result.

and why I'd like to do it :

I want to check values is IDictionary or not to do different logic, object value can be Array or Dictionary<int,int> or List





.NET5: Reading custom attributes of an assembly referencing AspNetCore.MVC

I've written a function to read assembly's custom attributes:

let getAttributes(assemblyPath: string) =
    let assembly = System.Reflection.Assembly.LoadFrom assemblyPath
    assembly.GetCustomAttributes() // <---

It works pretty well, as long as I don't try to load my project which references "Microsoft.AspNetCore.Mvc.Core". Then I get an exception from the line marked by // <---.

Could not load file or assembly "Microsoft.AspNetCore.Mvc.Core, Version=5.0.0.0, ...". The system can't find the file specified.

I though that it might have trouble finding the right location, so I provided a ResolveEventHandler:

let resolveEventHandler =
    ResolveEventHandler(fun _ args ->
        if(args.Name.StartsWith "Microsoft.AspNetCore.Mvc.Core") then
            System.Reflection.Assembly.LoadFrom """C:\Program Files\dotnet\packs\Microsoft.AspNetCore.App.Ref\5.0.0\ref\net5.0\Microsoft.AspNetCore.Mvc.dll"""
        else
            null

AppDomain.CurrentDomain.add_AssemblyResolve resolveEventHandler

But this brings another exception:

Reference assemblies shall not be loaded for execution. They can only be loaded in Reflection-only context.

I tried switching to Assembly.ReflectionOnlyLoadFrom, but that didn't help, as the operation is said not to be possible on my platform.

So... am I missing anything? Is there any better way of fetching Assembly Attributes without going that much into details?





(Kotlin) How can i execute lambda () -> Unit like function parameter through reflection

i have code

object Boo {
    val lambda: () -> Unit = { print("lambda") }
    operator fun invoke(init: Foo.() -> Unit){
    }
}

And I don't understand how can i execute init in reflection.


For example, I can execute lambda class member like this

    ((this.javaClass.kotlin
.declaredMemberProperties as List<*>)[0] asKProperty1<Boo,*>).invoke(this) //works

so init i get like parameter invoke function only

    val kparameter: KParameter = this.javaClass.kotlin.functions
.first { it.name == "invoke" }.parameters[0]

but i can't do anything with it!

Can anyone help me with this question?





C#: how to programmatically create a class library DLL using reflection?

Suppose my code possesses the knowledge about the metadata of a nonexistent class library "mytest.dll", such as the types in this library, the functions of the types, the parameters and return types of the functions, etc.

How does my code manufacture this DLL using techniques such as reflection?

I know my code can generate the "mytest.cs" text file, then execute the compiler to produce the DLL, then delete the "mytest.cs" file. Just want to know if there are "more advanced" or "cooler" ways to do it.

Thanks.





mardi 16 mars 2021

Can I get PropertyInfo for a field or property in a class without using reflection?

I have tried searching around using Expressions but not able to find something by which I can access the fields or properties of a class without using reflection.

Basically, I will get a string at runtime, and I know that that string will be a property of the class, but I need to validate that it indeed is a property inside that class.

e.g. If I have a class:

class Test { string a; public string b {get;set;} }

I get the string values a and b at runtime and I need to verify that they exist inside the class Test

What I know till now from researching is that I can do:

string one = "a";
string two = "b";
PropertyInfo result1 = typeof(Test).GetProperty(one);
PropertyInfo result2 = typeof(Test).GetProperty(two);

But this code is using reflection. I want to know if there is some way I can do this without using reflection?

Can I do this using Expressions?





Kotlin Reflection - Returns an instance with set properties values based on it's property name

I'm trying to create a function that returns any data class object setting it's property values with its property names (if all strings) without changing it's default values I have an example on how it is:

Imagine this data class:

data class StudentProfile(

    var fullName: String = "",

    var mobilePhone: String = "",

    var birthDate: String = "",

    var email: String = ""

)

I want to keep this empty default values, but I wanted a generic function that should work for any class and returns (in this case) this:


return StudentProfile( 
                mobilePhone = "mobilePhone",
                fullName = "fullName",
                email = "email",
                birthDate = "birthDate"
            )

Is it possible?





F# how to specify when creating union case value what value to set to which field?

I have a dictionary where the key is the name of the field, and the value is this field value. Is it possible to somehow explicitly indicate to which field what value to assign using this dictionary? Or is the only way to stick to the sequence of field declarations when passing the second argument to the FSharpValue.MakeUnion?





How can I change a number in a interface object from a variable in Java using something like Reflection or Javassist

I have a variable, which is a new interface. I would like to change something inside of that. I am not sure if this is possible with something like Reflection or Javassist.

This is fairly hard to explain, but if you look at the example you might understand me a bit better.

If you need more information, please ask because I really need to know this.

(this is code from ProtocolLib, which uses Netty. I want to patch something in ProtocolLib at runtime; hence I want to use something like Reflection or Javassist)

Here is an example:

final ChannelInboundHandler endInitProtocol = new ChannelInitializer<Channel>() {
    @Override
    protected void initChannel(final Channel channel) throws Exception {
        try {
synchronized (networkManagers) {
    if (MinecraftVersion.getCurrentVersion().getMinor() >= 12 /* I want to change this 12 to an 8 using Reflection or something like Javassist */) {
    channel.eventLoop().submit(() ->
injectionFactory.fromChannel(channel, ProtocolInjector.this, playerFactory).inject());
    } else {
        injectionFactory.fromChannel(channel, ProtocolInjector.this, playerFactory).inject();
    }
}
        } catch (Exception ex) {
reporter.reportDetailed(ProtocolInjector.this, Report.newBuilder(REPORT_CANNOT_INJECT_INCOMING_CHANNEL).messageParam(channel).error(ex));
        }
    }
};




Why doesn't LINQ .Distinct filter out the things that are evaluated to be equals by the same comparer?

See the following code sample (taken from a larger source)

Type plastHingeType1 = null;
Type plastHingeType2 = null;
foreach (Type type in
    (assembly.GetTypes().Concat(dynamicSerializers.Keys))
    // this distinct does not work as expected
    // note the equality comparer
    .Distinct(EqualityComparer<Type>.Default)
    )
{
    if (plastHingeType1 is null && type.Name == "PlasticHingeSettings")
    {
        plastHingeType1 = type;
    }
    else if (plastHingeType1 != null && type.Name == "PlasticHingeSettings")
    {
        plastHingeType2 = type;
    }
    // this will be true
    // even though it uses the same equality comparer that the .Distinct call used
    bool test = EqualityComparer<Type>.Default.Equals(plastHingeType1, plastHingeType2);

the problem is, that the linq .Distinct will not filter out a type, that should have been filtered out, because the specified comparer returns true to it and the previous occurence.

There is no paralell execution or anything extra around this code, what could be the problem?





Python dynamically add property always returns same result

I'm relatively new to python. I created this minimal sample to demonstrate my problem. Within a loop I add some properties to my class during runtime. If I query the properties later I always get the same result. I printed and checked the function instance variables of the function and the property and they all differ as expected. When I invoke the properties I always end up in the result of the last property.

class T:
    def __init__(self):
        specialList = ['MIN', 'DEF', 'MAX']
        for special in specialList:  
            def get_property_special(self):
                print('return get_current('+special+')') #call getter with special parameter
                return special # just fake here. Should return value of getter
            
            print("Dyn function", get_property_special)
            specialProp = property()
            print("Property "+ str(specialProp))
            specialProp = specialProp.getter(get_property_special)
            setattr(T, "current_" + special.lower(), specialProp)
            print ("define property: current_" + special.lower())
               
b = T()
print(b.current_max)
print(b.current_min)
print(b.current_def)

Results in:

Dyn function <function T.__init__.<locals>.get_property_special at 0x0000026D6D8805E0>
Property <property object at 0x0000026D6D8929A0>
define property: current_min
Dyn function <function T.__init__.<locals>.get_property_special at 0x0000026D6D8A9790>
Property <property object at 0x0000026D6D892AE0>
define property: current_def
Dyn function <function T.__init__.<locals>.get_property_special at 0x0000026D6D8A94C0>
Property <property object at 0x0000026D6D892B30>
define property: current_max
get_current(MAX) #ok
MAX
get_current(MAX) #Error: why MAX called min
MAX
get_current(MAX) #Error: why MAX called def
MAX

Edit: I want the property to call the getter with the parameter MIN, MAX, DEF





how to do reflection in Nested object vb.net

I have an object that I accept and this object is a nested object which means it has properties that are also objects and so on. I need a way to go through this object and its sons and their sons etc and for each of the properties check if its name is in the array I have with the names of some of the properties of the nested object and if so then I need the value of the property from the object. Is there a way to do that? I tried through reflection but could not move forward. Some of the properties of the object I do not need so I check for on a property whether it is in my array





lundi 15 mars 2021

Design an observer API where there is no direct coupling between observers and subjects and provide an implementation

https://github.com/bethrobson/Head-First-Design-Patterns/tree/master/src/headfirst/designpatterns/observer/weather

Here we have code. Could you please tell me how to implement observer API?





Passing dynamic class parameter at runtime - is it possible? [duplicate]

It was suggested I review this URL Pass An Instantiated System.Type as a Type Parameter for a Generic Class, and although it's similar, it is not the same - I'm not looking for an instance of a class to be passed to a consumer, but instead the definition of a class.

I'm working with an example I found online, and am trying to dynamically pass a class reference to its class with the following signature:

public class DataNamesMapper<TEntity> where TEntity : class, new()

A simple test, I can instantiate the DataNamesMapper class using this class:

public class Testing { }

with a simple call like:

var mapper1 = new DataNamesMapper<Testing>();
  • Success!

But at runtime, I want to dynamically pass a class to DataNamesMapper without directly referencing the class. This doesn't work:

Type testing = typeof(Testing);
var mapper2 = new DataNamesMapper<testing>();
  • 'testing' is a variable but is used like a type

In my case, I'm looping through a set of table names and using the TableName, want a reference to the class object/definition per below:

Dictionary<string, Type> dict = new Dictionary<string, Type>
{
  { "Schedules", typeof(Schedules) }
};
foreach (DataTable tbl in dsMira.Tables)
{
  Type myType = dict[tbl.TableName];
  var mapper3 = new DataNamesMapper<myType>();

  var classString = $"myNamespace.{tbl.TableName}";
  var objectType = Type.GetType(classString);
  var instantiatedObject = Activator.CreateInstance(objectType);
  var mapper4 = new DataNamesMapper<instantiatedObject>();
}

"mapper3" instance fails because it's just a rework of the "mapper2" approach.

  • 'myType' is a variable but is used like a type

and the "mapper4" approach I don't believe will ever work because the DataNamesMapper isn't expecting an instantiated object. Regardless, the error message is same:

  • 'instantiatedObject' is a variable but is used like a type

Is it possible to dynamically pass a class at runtime?





How to cause method calls enter a different method first

I don't even know how to properly title my question so any suggestions and I will change it. The problem I have is this; I have an object which has some dispose work to do. Using the "using" keyword and scope is not possible because the object can be in use for a long time. I do not want to rely on the programmer to remember call Dispose() on these objects because he might forget. Instead, I would want all or some methods of the object to work like this:

  1. All the methods first go into some general function
  2. This general function calls the original method
  3. Depending on a bool param (for example) of the general method, the general method finished by maybe doing some cleanup work (disposing)

So if I have 10 methods, I would want them all to enter the same place, do their work, and then dispose. And I do not want to repeat the call to the dispose method in each of the 10 methods.

Example:

public void SomeBaseFunc(bool shouldDispose) //all methods first get drained here
{
//call whatever original func that the client called
//query bool param and dispose
}




How do I create an instance of a generic type with a parameter of type list

I have a generic class Result that looks like this

public class Result<T>
{
    public List<Error> Errors { get; set; } = new List<Error>();

    public T ResultObject { get; set; }

    public Result(List<Error> errors)
    {
        Errors = errors;
        Success = false;
    }
}

I try to create an instance like this:

Activator.CreateInstance(typeof(TResponse), new object[] { failures.Select(x => new Error(x.ErrorMessage)).ToList() })

TResponse is of type Result<GetUserFlow>. GetUserFlow is a dto but not important in this case. When I run my code I get the following error:

System.MissingMethodException: Constructor on type 'Heimdall.Application.Result`1[[Heimdall.Application.Dtos.GetUserFlow, Heimdall.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found.

I guess the problem is that when passing a list as parameter it isn't seen as one parameter but as many. Each created Error is one parameter. I couldn't find anything about this topic.





Comparison of two objects without oids at all levels

I have such objcects:

import lombok.Builder;
import lombok.Data;

import java.util.List;

@Data
@Builder
public class Grandfather {
    private Integer oid;
    private String name;
    private List<Father> childs;
}

@Data
@Builder
public class Father {
    private Integer oid;
    private String name;
    private List<Son> childs;
}

@Data
@Builder
public class Son {
    private Integer oid;
    private String name;
}

I would like to compare two objects which are type of Grandfather by recursion method, that use also reflection. That method compare all fields of object at all level without field oid. Below I present the objects that should be treated as the same when compared:

Son son1 = Son.builder()
                .oid(100)
                .name("Paul")
                .build();
        Son son2 = Son.builder()
                .oid(null)
                .name("Paul")
                .build();
        Father father1 = Father.builder()
                .oid(32)
                .name("Alex")
                .childs(Collections.singletonList(son1))
                .build();
        Father father2 = Father.builder()
                .oid(567)
                .name("Alex")
                .childs(Collections.singletonList(son2))
                .build();
        Grandfather grandfather1 = Grandfather.builder()
                .oid(12)
                .name("John")
                .childs(Collections.singletonList(father1))
                .build();
        Grandfather grandfather2 = Grandfather.builder()
                .oid(1222)
                .name("John")
                .childs(Collections.singletonList(father2))
                .build();

I wrote this method but unfortunately it does not work. This method uses reflection through which it iterates through the objects (fields) of a given object. Unfortunately, it uses recursions badly.

public static boolean haveSameValuesExceptOneField(Class<?> type, Object t1, Object t2, String exceptGetter)
            throws Exception {
        for (Method m : type.getMethods()) {
            if (!m.getName().equals(exceptGetter) && isGetter(m)) {
                final Object o1 = m.invoke(t1);
                final Object o2 = m.invoke(t2);
                if (!Objects.equals(o1, o2)) {
                    return haveSameValuesExceptOneField(m.invoke(t2).getClass(), m.invoke(t1), m.invoke(t2), exceptGetter);
                }
            }
        }
        return true;
    }

private static boolean isGetter(Method method) {
        return method.getName().startsWith("get") && method.getParameterTypes().length == 0;
    }

This is how I call this method:

System.out.println(haveSameValuesExceptOneField(Grandfather.class, grandfather1, grandfather2, "getOid"));

How can I fix this method to make it work the way I want?





Reify generic class reflection given parameter class reflection

I have a generic class that I need to return complete type info for, and I have the class information for the generic parameter type. How might I upgrade the class information for the generic type parameter?

public class MyClass<T> {
  String key;
  T value;

  Class<MyClass> getTypeInfo(Class<T> cls) {
    // How do I upgrade this with the reified type info in cls?
    return MyClass.class;
  }
}

Ultimately, I'm writing a deserialization schema for Flink, and Need to return a reified class information in getProducedType as part of the interface. The class returned by the deserializer is a something like MyClass where I know the class information of T.

https://www.logicbig.com/how-to/code-snippets/jcode-reflection-class-gettypeparameters.html





how to get make object of enum in reflection in java

I need get name from Enum with reflection of java.

I know I can that for class: (but I could not find it about Enums)

public class EnumWrapper<T> {

    @SuppressWarnings("unchecked")
    public String getType() {
        Type type = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) type;
        Class<T> entity = (Class<T>) pt.getActualTypeArguments()[0];
        String name = t.getClass().getName();

        return name;
    }
}

I maybe set any of the Enums :

public enum Gender {
    WOMAN, MAN, OTHER
}

public enum Language {
    Norwegian, ENGLISH, PERSIAN
}




Exception thrown from Expression.Lambda in AOT

Expression.Lambda(exp, parameters);

It completely works in JIT. For AOT, it works with <= 15 parameters.

for 16 parameters, exception was thrown as follow:

System.NotImplementedException: byref delegate
at System.Linq.Expressions.Interpreter.LightLambda.CreateCustomDelegate (System.Type delegateType) <0x1052b3620 + 0x00738> in <b17c8f8ec0e94e6aa946d54abe0cfd86#d5047ea47da6b88a294b7510b13ff6ef>:0
at System.Linq.Expressions.Interpreter.LightLambda.MakeDelegate (System.Type delegateType) <0x1052b3da0 + 0x0005f> in <b17c8f8ec0e94e6aa946d54abe0cfd86#d5047ea47da6b88a294b7510b13ff6ef>:0
at System.Linq.Expressions.Interpreter.LightDelegateCreator.CreateDelegate (System.Runtime.CompilerServices.IStrongBox[] closure) <0x1052ac220 + 0x0006f> in <b17c8f8ec0e94e6aa946d54abe0cfd86#d5047ea47da6b88a294b7510b13ff6ef>:0

for >= 17 parameters, exception was thrown as follow:

System.PlatformNotSupportedException: Operation is not supported on this platform.
at System.Linq.Expressions.Compiler.DelegateHelpers.MakeNewCustomDelegate (System.Type[] types) [0x00000] in <00000000000000000000000000000000>:0
at System.Linq.Expressions.Compiler.DelegateHelpers.MakeNewDelegate (System.Type[] types) [0x00000] in <00000000000000000000000000000000>:0
at System.Linq.Expressions.Compiler.DelegateHelpers.MakeDelegateType (System.Type[] types) [0x00000] in <00000000000000000000000000000000>:0
at System.Linq.Expressions.Expression.Lambda (System.Linq.Expressions.Expression body, System.String name, System.Boolean tailCall, System.Collections.Generic.IEnumerable`1[T] parameters) [0x00000] in <00000000000000000000000000000000>:0

I know AOT should not compile any expressions in runtime, it will affect the performance as there is a fallback process. So I am not asking about the best approach, just want to figure out why exceptions were thrown when too many parameters but works with <= 15 parameters in AOT.





Blocking phone calls in Android before API 28

I have found code to programatically block phone calls in Android here, and the following code works:

    val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    val m1 = telephonyManager::class.java.getDeclaredMethod("getITelephony")
    m1.isAccessible = true
    val telephonyService = m1.invoke(telephonyManager)
    val m2 = telephonyService::class.java.getDeclaredMethod("silenceRinger")
    val m3 = telephonyService::class.java.getDeclaredMethod("endCall")
    m2.invoke(telephonyService)
    m3.invoke(telephonyService)

However, the above code blocks all subsequent phone calls until the device is restarted on API 26 and 25. All other posts on Stackoverflow give a similar solution to this.

Is there a solution for Android before API 28 that just blocks the current phone call?





CreateDelegate() System.ArgumentException method signature mismatch

I've been trying to use reflection to compare objects whose type is not known at compile time, and rather than calling Invoke() every time I'm trying to use CreateDelegate(). I've gotten it working thus far in a generically typed class for primitives and the like, but I've run into a brick wall with objects of type KeyValuePair<TKey,TValue>. It throws with

System.ArgumentException: 'Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.'

when CreateDelegate() is called even though the method signature matches the types provided to and returned from Invoke(), and I can't figure out what it is I'm doing wrong. The minimal code to reproduce the exception is below:

static void Main(string[] args)
{
    var kvp = new KeyValuePair<string, string>("test key", "test value");

    var getKeyMethod = typeof(KeyValuePair<string, string>).GetProperty("Key").GetGetMethod();
    Console.WriteLine(getKeyMethod.Invoke(kvp, null));  //works fine

    var getKey = (Func<KeyValuePair<string, string>, string>) getKeyMethod.CreateDelegate(typeof(Func<KeyValuePair<string, string>, string>));  //exception thrown here
    Console.WriteLine(getKey(kvp));  //never gets here
}

I realize the same thing is possible using expression trees, and I have gotten that working using the same exact method signature, as below:

    ParameterExpression targetExp = Expression.Parameter(typeof(KeyValuePair<string, string>), "target");
    MemberExpression propertyExp = Expression.Property(targetExp, typeof(KeyValuePair<string, string>).GetProperty("Key"));
    var getKeyMethod = Expression.Lambda<Func<KeyValuePair<string, string>, string>>(propertyExp, targetExp).Compile();

All the same, I'd like to understand just what is going wrong here (expression trees are also a bit slower, but I'm mostly just annoyed that I can't get this working).





dimanche 14 mars 2021

invoke method when I get the parameters like this : Object... args

this is what I need to do:

  • invokes a method that returns an int value, on the given instance.

    • the method to invoke will be given by its name only.
    • You can assume that there is exactly one such method and that
    • the method is declared on the instance itself and not as part of its inheritance chain
    • @param methodName the name of the method to invoke
    • @param args the arguments to pass to the method, if such exists.
    •         Note: You should not use the arguments in order to extract and identify the method.
      
    •               You can do that only (and simply) by its name.
      
    •               You just need to pass the arguments AS IS to the method invocation...
      
    • @return the result returned from the method invocation */

    int invokeMethodThatReturnsInt(String methodName, Object... args);

this is what I did





C++ static reflection TS: would it support assign/call by name?

There is a C++ Technical Specification on static reflection (current PDF draft and cppreference page) which might move into C++23 or later.

Would it be possible in the current draft (I understand syntax is perhaps not fixed yet) to access struct fields / call class member functions by name?

For instance

struct Test {
  int x;
  int y; 
};

Test foo;

auto meta = reflexpr(foo);  // access meta information about class

some_magic_setter<"x", meta>(foo, 5);  // ??? 

Would this be possible and if yes how ?





c# Accessing specific members of a class with a list without Reflection

I want to check specific fields of a class for content. If there is no value, it should give a message. The current example is working. But I am looking for a way to to the same without Reflection.

using System;
using System.Reflection;

namespace ConsoleApp1
{
    class Program
    {
       static void Main(string[] args)
       {
           TableDescription table1 = new TableDescription { BUYER_AID = 0, DESCRIPTION_LONG = 3, EAN = 2, SUPPLIER = 17};
           TableDescription table2 = new TableDescription();
           string [] members = new string[] { "BUYER_AID", "DESCRIPTION_LONG", "EAN" };
           CheckAndSetValue(table1, table2, members);
       }

       static void CheckAndSetValue(TableDescription t1, TableDescription t2, string[] list)
       {
           foreach (string name in list)
           {
               Type type = typeof(TableDescription);
               FieldInfo typeinfo = type.GetField(name);
               short value = Convert.ToInt16(typeinfo.GetValue(t1));
               if (0 != value)
               {
                   typeinfo.SetValue(t2, value);
               }
               else
               { 
                    Console.WriteLine($"Value for {name} is missing!");
               }
           }
       }
   }
   public class TableDescription
   {
       public short BUYER_AID = 0;
       public short DESCRIPTION_LONG = 0;
       public short EAN = 0;
       public short SUPPLIER = 0;
   }
}

Is there a way to to it something like:

var[] members = new var[]{TableDescription.BUYER_AID, TableDescription.DESCRIPTION_LONG, TableDescription.EAN};

I am looking for a solution to work without stings. Working with Strings will make trouble with refactoring and on error it will crash during runtime.





samedi 13 mars 2021

Metadata on methods of a class with copied properties changes on changing the metadata of the source class - Typescript

Sorry for the verbose title. I have a class MutateMe passed into a factory called FilterFactory by a decorator Decorator.

export const Decorator = (options?: DecoratorOptions) => <T extends Constructor>(target: T) => {
  new FilterFactory(target, options);
}

Within this factory, I'm copying over the methods onto the target class and setting its metadata.

export class FilterFactory {
  constructor(protected target: any, options: DecoratorOptions) {
    // Getting the reference to the class from where I want to copy over methods with their own metadata
    const routesController = FilterController;

    // The class itself consists of a prefix that must be prepended to all its member methods' metadata.
    const prefixRoute = getControllerPrefix(routesController);

    console.log("For each key (member name)")
    Reflect.ownKeys(routesController.prototype).forEach(
      (property) => {
        // Ignore the primitive class methods
        if (!['constructor', 'toString', 'length'].includes(property.toString())) {
          // Copy the methods over to the `target`
          Object.defineProperty(
            target.prototype,
            property,
            Object.getOwnPropertyDescriptor(
              routesController.prototype,
              property
            )
          )

          // Prepends class metadata `filter` to each route method's metadata
          patchRoutes(target.prototype[property], prefixRoute)

          // NOTE: An alternative to prototype property assignment (Doesn't work either)
          // target.prototype[property] = routesController.prototype[property]
          
          console.log(Reflect.getOwnMetadata(PATH_METADATA, target.prototype[property]))
        }
      })
  }
}

The patchRoutes function is like so:

const patchRoutes = <K, T extends string, P>(patchee: any, patches: (T | T[] | ((...args: P[]) => (T | T[]))), ...args: P[]) => {
  const existingPath = Reflect.getOwnMetadata(PATH_METADATA, patchee)
  if (patches instanceof Function) { patches = patches(...args) }
  if (!Array.isArray(patches)) patches = [patches]

  Reflect.defineMetadata(PATH_METADATA, (existingPath === "/" ? [...patches] : [...patches, existingPath]).join("/"), patchee)

  const createResetCallback = (resetValue, resetTarget) => () =>
    Reflect.defineMetadata(PATH_METADATA, resetValue, resetTarget)

  return createResetCallback(existingPath, patchee)
}

It returns a reset callback to reset the patched metadata.

Now, when I decorate more than one classes with this decorator, I can see a duplication of patching.

For example, patching once would give me foo/filter/... and for the second call, it'd give me bar/filter/filter/....

I wanted to see if it was the problem of copying methods over improperly, so, I tried patching the base class, copy over the patched methods and reset the metadata of the base class:

const propertyResetCb = patchRoutes(routesController.prototype[property], prefixRoute)
...
// Assigning the property now to the target
...
// Calling the reset callback
propertyResetCb()

However, this seems to reset the property of all the decorators that I've made.

This leads me to believe that it's using a singular prototype reference for the copied over methods. I'd wish to copy them free of reference (clone if you will) so that I can independently set their metadata.

Also, I'd prefer if I didn't have to modify the patchRoutes to factor in the duplication because, in the end, I'd like to do more modifications to their individual metadata separately.

Thanks :)





vendredi 12 mars 2021

How can I get the inner type of a generic class in Kotlin?

I know with Kotlin (on the JVM) I can get the type of a class with foo::class. And I know I can generic information, even at runtime, with typeOf<>() (as long as my function is inline). But I can't figure out how to get Int from a List<Int> for example.

Here's as far as I can get:

import kotlin.reflect.KType
import kotlin.reflect.typeOf

fun main() {
    TypeTest.get<Int>()
    TypeTest.get<List<Int>>()
    TypeTest.get<Map<String, List<Int>>>()
}

class TypeTest {
    companion object {
        @OptIn(ExperimentalStdlibApi::class)
        inline fun <reified OUT : Any> get() {
            generateReturnType(typeOf<OUT>())
        }

        fun generateReturnType(type: KType) {
            val classifier = type.classifier!!
            println("class $classifier has parameters ${classifier::class.typeParameters}")
        }
    }
}

This prints:

class class kotlin.Int has parameters [T]
class class kotlin.collections.List has parameters [T]
class class kotlin.collections.Map has parameters [T]

Given a KClassifier, how can I get its inner type (ideally recursively, in the case of a List<List<Int>>)? Or is there another way to do this?





Java Reflection with arrays based upon inner class definition

Given this Java structure:

class  Master
{
  static class innerThing 
  {
    static StringBuilder  NumOfThings      = new StringBuilder( 2);
    
    static class   Thing_def
    {
      static StringBuilder  field1         = new StringBuilder( 3);
      static StringBuilder  field2         = new StringBuilder( 3);
      static StringBuilder  field3         = new StringBuilder(13);
    }
    
    static Thing_def[]  Things = new Thing_def [2];
    static { for (int i=0; i<Things.length; i++)  Things[i] = new Thing_def();  }
  }
}

Using Reflection in this bit of code:

    Field[] FieldList = DataClass.getDeclaredFields();
    if (0 < FieldList.length )
    {
      SortFieldList( FieldList );

      System.out.println();
      for (Field eachField : FieldList)
       {
         String fldType = new String( eachField.getType().toString() );

         if ( fldType.startsWith("class [L") )
            System.err.printf("\n@@@ fldType= '%s'\n", fldType);  //$$$$$$$$$$$$$$$

         if ( fldType.startsWith("class java.lang.StringBuilder") )
         {
           g_iFieldCnt++;
           String str = DataClass.getName().replaceAll("\\$",".");
           System.out.printf("%s.%s\n", str, eachField.getName() );
         }//endif
       }//endfor
    }//endif

I get the following output: (Notice that it shows one copy of the fields in Thing_def.)

Master.innerThing.NumOfThings

@@@ fldType= 'class [LMaster$innerThing$Thing_def;'

Master.innerThing.Thing_def.field1
Master.innerThing.Thing_def.field2
Master.innerThing.Thing_def.field3

In another part of the system I access the fields to generate a CSV file:

    Field[] FieldList = DataClass.getDeclaredFields();

    if (0 < FieldList.length )
    {
      for (Field eachField : FieldList)
       {
         String fldType = new String( eachField.getType().toString() );

         if ( fldType.startsWith("class java.lang.StringBuilder") )
         {
           Field  fld = DataClass.getDeclaredField( eachField.getName() );
           StringBuilder sb = (StringBuilder)fld.get(null);

           CSV_file.printf("%s,", sb );   // emit column to CSV
    
           //fld.set( DataClass, new StringBuilder() );
         }//endif

       }//endfor
       
    }//endif

So in this case I actually will need to directly access array elements.
That is, I need to get at each Master.innerThing.Thing[n].field

So, the big question is:

How do I generically access arrays like this ?

How do I know that Thing_def does not have data, it is merely a structural definition for Things[ ] ?





Operator 'is' with type, retrieved by Reflection

How to implement operator 'is' with a type, that I got from reflection (since that type marked as internal)? My code:

    Type someType = someObj.GetType();
    Type runtimeType = Assembly.GetAssembly(typeof(string)).GetType("System.RuntimeType");  //Marked as internal

    if (someType is runtimeType)    //Not compiling...
    {
        //To do something
    }

I wrote some hackery code, but may be there is a better solution than that:

    private static bool _isThat<T, K>(T obj) { return obj is K; }

    private static readonly MethodInfo _isThatMethodInfo = typeof(Program).GetMethod("_isThat", 
        BindingFlags.NonPublic | BindingFlags.Static);

    public static bool IsThatType<T>(T obj, Type type)
    {
        return type == null || obj == null ? false
            : (bool)_isThatMethodInfo.MakeGenericMethod(typeof(T), type).Invoke(null, new object[] { obj });
    }

Unfortunately, method IsSubclassOf returns false if someType == runtimeType.





Reflecting into a class without FQCN

Is it possible to reflect into a class without knowing the fully qualified class name?

e.g. instead of this...

(new ReflectionClass(\App\Modules\Companies\Models\Company::class));

...something like this?

(new ReflectionClass('Company'));




jeudi 11 mars 2021

Getting the name of a variable passed by reference

Similar to Finding the variable name passed to a function

The main difference is that I'm using a variable passed by reference, and in particular, I don't actually have an object instance at the time that I'm calling the nameof function

For example:

class blank 
{
}
class Program
{

   static blank yes;

    static void test<T>(ref T no)
    {
        Console.WriteLine(nameof(no));  //outputs no
    }

    static void Main(string[] args)
    {
        test(ref yes);
    }
}

Is there a way to get "yes" printed instead of "no"? It feels like because I'm passing it by reference, there should be a way I can get at the actual name somehow.





Is it possible to get a list of class names those are implements a particular interface using Java Reflection?

For example:

interface Root<T> {
    public T getValue();
}

class A implements Root<String> {
    public String getValue() {
        return "";
    }
}

class B implements Root<Integer> {
    public int getValue() {
        return 0;
    }
}
  1. Is it possible to get a class details that are implemented Root interface via Java Reflection? I want the answer like this: [class A details, and class B details]
  2. In reflection, we can able to fetch method details via Method objects. Is it possible to identify a particular method is an interface method, ie: it is an override method but its signature is defined in that particular interface. For eg: I get Class B methods list, is it possible to identify getValue() is overridden method and its signature is defined in the Root interface?




Check annotation on a variable in kotlin data class

I have to check if a particular variable inside a kotlin data class has an annotation present or not.

Annotation class

annotation class Test(
    val identifier: String
)

Data class

data class Player(
    val name: String,
    @property:Test("stance")
    val stance: String,
    @property:Test("check")
    val check: String
)

I have to check if a particular variable inside this player object has the Test annotation present or not.

fun execute(player: Player) {

   //while this works, but i have to check for a specific variable
    player::class.members.forEach{
        val testAnnotation = it.findAnnotation<Test>()
        if(testAnnotation != null) {
            // DO something
        }
    }


I need to do something like
      player.check.hasAnnotation<Test>()

}

Would appreciate any help here, TIA





C# : Making generic type at runtime

I have an interface

public interface IBsonClassMap<T> 
    where T : class
{
    void Configure(BsonClassMap<T> map);
}

which serves as base for all mappings for mongo collections.

An implementation of it looks like this

public class StudentClassMap : IBsonClassMap<Student>
{
    void IBsonClassMap<Student>.Configure(BsonClassMap<Student> map)
    {
    }
}

I'm using an extension method to scan an assembly and invoke each mapping found.

This is it.

    public static void ApplyConfigurationFromAssemblies(this IServiceCollection services, params Assembly[] assemblies)
    {
        Type _unboundGeneric = typeof(IBsonClassMap<>);

        List<(Type Type, Type Handler, Type Argument)> types = new List<(Type, Type, Type)>();

        foreach (Assembly assembly in assemblies)
        {
            types.AddRange(assembly
                .GetExportedTypes()
                .Where(type =>
                {
                    bool implementsType = type.GetInterfaces().Any(@interface => @interface.IsGenericType && @interface.GetGenericTypeDefinition() == _unboundGeneric);

                    return !type.IsInterface && !type.IsAbstract && implementsType;
                })
                .Select(type =>
                {
                    Type @inteface = type.GetInterfaces().SingleOrDefault(type => type.GetGenericTypeDefinition() == _unboundGeneric);
                    Type argument = @inteface.GetGenericArguments()[0];

                    return (type, @inteface, argument);
                }));
        }

        types.ForEach(type =>
        {
            object classMapInstance = Activator.CreateInstance(type.Type);

            Type unboundGeneric = typeof(BsonClassMap<>);
            Type boundedGeneric = unboundGeneric.MakeGenericType(type.Argument);

            type.Handler.GetMethod("Configure").Invoke(classMapInstance, new object[] { boundedGeneric });
        });
    }

The issue is taht I'm getting

Object of type 'System.RuntimeType' cannot be converted to type 'MongoDB.Bson.Serialization.BsonClassMap`1[Platform.Concepts.Mongo.Collections.Student]'.

Also, everything works as expected if I'm removing the argument in the Configure method of the IBsonClassMap, and addapt everhting accordingly. The method ends up getting invoked.

So instead of this

  type.Handler.GetMethod("Configure").Invoke(classMapInstance, new object[] { boundedGeneric });

I have this

   type.Handler.GetMethod("Configure").Invoke(classMapInstance, null);