dimanche 31 octobre 2021

Invoking a method with EF core dbContext to test with dummy data

I want to test a method (GetProjectInfo) from "AppManager" class using invoke,

AppManager.cs is as follows

public AppManager(Configuration configuration,
            AppClient client,
            Manager _manager,
            TicketCreator ticketCreator,
            EmailCatalog emailCatalogConfig,
            CommonConfiguration commonConfiguration,
            Entities entities,
            IBackgroundJobClient jobClient,
            FMSManager fmsManager)
        {
            _configuration = configuration;
            _manager = manager;
            _ticketCreator = ticketCreator;
            _commonConfiguration = commonConfiguration;
            _entities = entities;
            _jobClient = jobClient;
            _emailCatalogConfig = emailCatalogConfig;
            _client = client;
            _client.SetAuthenticationToken(GetAuthenticationToken());
            _fmsManager = fmsManager;
        }

In above class, Entities is nothing but a DBcontext EF core class,

 public partial class Entities : DbContext
    {

        public Entities()
        {
        }

        public Entities(DbContextOptions<Entities> options)
            : base(options)
        {
        }
      
.......All  DbSet properties
.......OnModelCreating(ModelBuilder modelBuilder)

So to test/invoke this method I have created a console app with below code

 static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Assembly assembly = Assembly.LoadFile("dll path");
            Type type = assembly.GetType("AppManager");

            MethodInfo methodInfo = type.GetMethod("GetProjectInfo");

            ParameterInfo[] parameters = methodInfo.GetParameters();
            object[] parametersArray = new object[] { "939f378161c42d85658fb2d77f497e0f" };

            **var options = new DbContextOptionsBuilder<Entities>()
                           .UseInMemoryDatabase(databaseName: "db_name")
                           .Options;
            Entities _entities = new Entities(options);**

            object[] contructorArray = new object[] { null, null, null, null, null, null, _entities, null, null };

            object result = null;

            object classInstance = Activator.CreateInstance(type, contructorArray);

            result = methodInfo.Invoke(classInstance, parametersArray);

So to invoke the method from AppManager class I need to pass Entities to constructor param which I did as heighted bold above. But with this I am not able to connect to db.

Error I am getting here is,

System.MissingMethodException: 'Constructor on type 'AppManager' not found.'





Creating an object without its known type

I was wondering how can I create an object if type of this object is stored in a string. My goal is to optimise it as good as it's possible, this algorithm will be iterated many times. I know 3 possible solutions:

  1. Creating a list (vector?) of possible classes and iterating over all possible variants (slow as hell if i have >10 possible classes)
  2. std::map approach (creating a map and checking all of it) (performance not checked)
  3. Using Boost::PFR (kind of "reflection" library for C++) (performance also not known)

Do you know which approach would be the best and fastest options? And how to implement that? Sincerely, Karol





How can a Java library detect annotated methods?

There are many ways to find all methods with a specific annotation if you know the package you're searching in (for example by using the Reflections library). But if I'm writing a library, then I don't know the name of the package that's using my library. How would I go about finding all methods with a specific annotation in a case like this?





samedi 30 octobre 2021

Is it possible to change the "instruction segment" of a c program during its execution?

According to this article, a c program has these sections:

  1. Text segment (i.e. instructions)
  2. Initialized data segment
  3. Uninitialized data segment (bss)
  4. Heap
  5. Stack

The "Text segment" (or "instruction segment") stores the executable instructions of the program.

Is it possible to write a c program that access this memory region and that makes changes on it, changing the instructions that the program will execute?





Cannot cast reflection field into Map

I was trying to get cast reflection field to Map, but it gives me this error:

java.lang.ClassCastException: java.lang.reflect.Field cannot be cast to java.util.Map

How do I fix this?

Minimal Reproducible Example:


open class Base {
    var inherited: Map<String, String> = mapOf(Pair("testing", "testing"))
}

class Child: Base() {
    var notInherited: Int = 100
}


fun main() {
    val c = Child()
    var inheritedMap: Map<String, String> = c.javaClass.superclass.getDeclaredField("inherited") as Map<String, String> 
    println(inheritedMap)
}

link to code playground: https://pl.kotl.in/xW8g4pNsX





Why usage of dynamic throws exception in runtime?

I have an external dll I'm loading into my appdomain during runtime.

I'm creating an instance of a class from that assembly into a local dynamic variable.

As far as I understood the usage of dynamic in C#, I can simply call a method of it, which will be resolved at run time...

Using this approach, the following code gets me a runtime "'object' does not contain a definition for 'Get'" exception.

I'll try to illustrate the structure as I can't expose the actual code.

External dll name: a.b.c

namespace Ext
{
  public static class FactoryCreator
  {
    public static ProxyFactory CreateFactory()
    {
        return new ProxyFactory();
    }
  }


  public interface FactoryIfc
  {
    Proxy Get();
  }

  internal class ProxyFactory: FactoryIfc
  {
    private Proxy proxy;

    public Proxy Get()
    {
      if (this.proxy == null)
        this.proxy = <a method to create a proxy>
      return this.proxy;
    }
  }
}

I'm using the following code

var assembly = "a.b.c, Version=1.0.0.0, Culture=neutral, PublicKeyToken=<key>,processorArchitecture=MSIL";
var instName = "Ext.FactoryCreator";
dynamic factoryCreator = AppDomain.CurrentDomain.Load(assembly).GetType(instName).GetMethod("CreateFactory").Invoke(null, new object[0]);
dynamic factory = factoryCreator.CreateFactory();
dynamic proxy = factory.Get();

I understand that for FactoryCreator dynamic variable, I need to get the Type and invoke the static method of it, but.. as I said, it is throwing an exception "'object' does not contains a definition for 'Get'" - at the factory.Get() statement - while I would expect dynamic factory to be resolve automatically to the object and service the Get() call.

Observing the situation under a debug session, I can clearly see the Get method using factory.GetType().GetMethods() in the quickwatch window.

Can you explain what is happening?

enter image description here

Must I use factory.GetType().GetMethod("Get") followed by an Invoke? I thought the power of dynamic should work this out automatically in runtime...





vendredi 29 octobre 2021

Create Delegate From ComObject Method (via Reflection)

I am able to retrieve it from a COM object via Reflection and run it with the MethodInfo.Invoke method.

However, I am trying to create a Delegate to be faster because I will use it in a loop. Unfortunately, I couldn't find a solution to the error message below. How can I create a delegate for a COM method?

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

My Delegate:

Public Delegate Function GetDriveNameDelegate(path As String) As String

My test Button:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

      Dim fsoType As Type = Type.GetTypeFromProgID("Scripting.FileSystemObject")
      Dim fsoInstance As Object = Activator.CreateInstance(fsoType)

      'Dim result As Type

#Region " This is working... "

      'Dim dispatch As IDispatchInfo = fsoInstance

      'dispatch.GetTypeInfo(0, 0, result)

      'Dim mi As MethodInfo = result.GetMethod("GetDriveName")

      'Dim param = New Object() {"C:\Windows"}

      'MessageBox.Show(mi.Invoke(fsoInstance, param))

#End Region

#Region " This is not working... "

      Dim fsoDelegate As GetDriveNameDelegate = GetDelegateFromCOM(fsoInstance, "GetDriveName")

      MessageBox.Show(fsoDelegate.Invoke("C:\Windows"))

#End Region

   End Sub   

My Delegate creator function:

   Public Function GetDelegateFromCOM(comObj As Object, methodName As String) As GetDriveNameDelegate
      Dim result As Type

      CType(comObj, IDispatchInfo).GetTypeInfo(0, 0, result)

      Dim mi As MethodInfo = result.GetMethod(methodName)

      Return [Delegate].CreateDelegate(GetType(GetDriveNameDelegate), mi, True)
   End Function

The IDispatch Interface:

<ComImport>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
<Guid("00020400-0000-0000-C000-000000000046")>
Public Interface IDispatchInfo
   ''' <summary>
   ''' Gets the number of Types that the object provides (0 or 1).
   ''' </summary>
   ''' <param name="typeInfoCount">Returns 0 or 1 for the number of Types provided by <see cref="GetTypeInfo"/>.</param>
   ''' <remarks>
   ''' http://msdn.microsoft.com/en-us/library/da876d53-cb8a-465c-a43e-c0eb272e2a12(VS.85)
   ''' </remarks>
   <PreserveSig>
   Function GetTypeInfoCount(ByRef typeInfoCount As Integer) As Integer

   ''' <summary>
   ''' Gets the Type information for an object if <see cref="GetTypeInfoCount"/> returned 1.
   ''' </summary>
   ''' <param name="typeInfoIndex">Must be 0.</param>
   ''' <param name="lcid">Typically, LOCALE_SYSTEM_DEFAULT (2048).</param>
   ''' <param name="typeInfo">Returns the object's Type information.</param>
   ''' <remarks>
   ''' http://msdn.microsoft.com/en-us/library/cc1ec9aa-6c40-4e70-819c-a7c6dd6b8c99(VS.85)
   ''' </remarks>
   Sub GetTypeInfo(typeInfoIndex As Integer, lcid As Integer, <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(TypeToTypeInfoMarshaler))> ByRef typeInfo As Type)

   ''' <summary>
   ''' Gets the DISPID of the specified member name.
   ''' </summary>
   ''' <param name="riid">Must be IID_NULL.  Pass a copy of Guid.Empty.</param>
   ''' <param name="name">The name of the member to look up.</param>
   ''' <param name="nameCount">Must be 1.</param>
   ''' <param name="lcid">Typically, LOCALE_SYSTEM_DEFAULT (2048).</param>
   ''' <param name="dispId">If a member with the requested <paramref name="name"/>
   ''' is found, this returns its DISPID and the method's return value is 0.
   ''' If the method returns a non-zero value, then this parameter's output value is
   ''' undefined.</param>
   ''' <returns>Zero for success. Non-zero for failure.</returns>
   ''' <remarks>
   ''' http://msdn.microsoft.com/en-us/library/6f6cf233-3481-436e-8d6a-51f93bf91619(VS.85)
   ''' </remarks>
   <PreserveSig>
   Function GetDispId(ByRef riid As Guid, ByRef name As String, nameCount As Integer, lcid As Integer, ByRef dispId As Integer) As Integer

   ' NOTE: The real IDispatch also has an Invoke method next, but we don't need it.
   ' We can invoke methods using .NET's Type.InvokeMember method with the special
   ' [DISPID=n] syntax for member "names", or we can get a .NET Type using GetTypeInfo
   ' and invoke methods on that through reflection.
   ' Type.InvokeMember: http://msdn.microsoft.com/en-us/library/de3dhzwy.aspx
End Interface




Call reflected constructor with default parameters in Kotlin

I'm restoring complex data from json files and some of them requires call for specific types that does not have empty constructors, but constructors with default parameters.

There is a method for creation an empty object,

abstract class Restorer {
        inline fun <reified T>load(ctx: T): T {
             var that: T = reset(ctx)
             // ...
        }

        inline fun <reified T>reset(ctx: T): T {
            val primaryConstructorT = T::class.constructors.find {
                it.parameters.isEmpty() || it.parameters.all { prm ->  prm.isOptional }
            }
            return primaryConstructorT!!.call() // <--- here is a problem
        }
}

So in some cases primaryConstructorT is a reflection for constructor with optional params, but direct call for that produces an exception. Callable expects 2 arguments, but 0 were provided.

There is the case for creation simple data class

data class DataClass (val foo: List<String> = listOf(), val bar: List<Int> = listOf())
// ...
var context: DataClass? = null;
// ...
context = Restorer.load(context)

Is there any method to call it





Why does Type.GetField may return null when the field indeed exists? [duplicate]

In the following class diagram, you can see that in the hierarchy there are two fields:

  • Location which is protected
  • Settings which is private

enter image description here

While performing reflection to get information about these fields using:

GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)

No matter how hard I'd try, the method would always return null for Settings; this, unless I change its visibility to something else than private; that doesn't makes sense at all because it simply works for other fields in the hierarchy that are private.

Also, according the docs, FlattenHierarchy is of no help since it targets static members.

The environment I'm doing this in is Unity 2021.2 which uses stock .NET Standard 2.1, well, at least that's my theory as the DLL hash is exactly the same as the one in:

C:\Program Files\dotnet\packs\NETStandard.Library.Ref\2.1.0\ref\netstandard2.1\netstandard.dll

In an attempt to solve this problem, I skimmed through Unity sources and stumbled upon an equivalent of the following code:

static FieldInfo? GetField(Type type, string name)
{
    var current = type;

    while (current != null)
    {
        var field = current.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        if (field != null)
        {
            return field;
        }

        current = current.BaseType;
    }

    return null;
}

This obvisouly works as that piece of code searches on the base types as well for the field.

Though my problem is solved with this code, it's a bit mysterious as on why is this really needed.

Actually I need this to fetch attributes out of a SerializedProperty:

using System;
using System.Reflection;
using JetBrains.Annotations;
using UnityEditor;

namespace abcd
{
    public static class SerializedPropertyExtensions
    {
        public static T GetPropertyAttribute<T>(this SerializedProperty property) where T : Attribute
        {
            if (property == null)
                throw new ArgumentNullException(nameof(property));

            var info = property.GetPropertyInfoPrivate();

            var attribute = info.FieldInfo?.GetCustomAttribute<T>();

            return attribute;
        }

        private static (object? Parent, FieldInfo FieldInfo, object Value, Type Type) GetPropertyInfoPrivate(this SerializedProperty property)
        {
            if (property == null)
                throw new ArgumentNullException(nameof(property));

            var parent = (object)property.serializedObject.targetObject;
            var field  = default(FieldInfo);
            var value  = (object)property.serializedObject.targetObject;
            var type   = value.GetType();
            var split  = property.propertyPath.Split('.');

            foreach (var name in split)
            {
                parent = value;
                field  = GetField(type, name);
                value  = field.GetValue(value);
                type   = field.FieldType;
            }

            return (parent, field!, value, type);
        }

        private static FieldInfo GetField(Type type, string name)
        {
            var current = type;

            while (current != null)
            {
                var field = current.GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                if (field != null)
                {
                    return field;
                }

                current = current.BaseType;
            }

            throw new InvalidOperationException();
        }
    }
}

The actual implementation of the above diagram is as follows (trimmed):

internal abstract class BaseImporter : ScriptedImporter
{
    [SerializeField]
    protected string Location = null!;
}

internal abstract class BaseImporterAtlas : BaseImporter
{
    [SerializeField]
    private BaseImporterAtlasSettings Settings = null!;
}

[Serializable]
internal class BaseImporterAtlasSettings
{
    [Min(0)]
    public int Padding;

    [Min(0)]
    public int Bleeding;

    public bool Translucency;

    public BaseImporterAtlasSettings(int padding, int bleeding, bool translucency)
    {
        Padding      = padding;
        Bleeding     = bleeding;
        Translucency = translucency;
    }
}

Question:

Why does a plain call to GetField(...) returns null in this case while it shouldn't really?

Is this a bug or am I missing something in the docs of GetField?





Anonimous class generation at runtime with reflection from dao template

Giving this context:

I have an InstrumentDao class in hibernate, it could have some child class like DrumDao, or GuitarDao. The traditional way is to have this classes extending InstrumentDao, but I can't do that because of requeriment.

Instead, I have to read the name and properties of the child class from a json, properties, or yml file, and then recover the data from the database.

For example I want an instrument that is a guitar, I search for the properties of a guitar and then I create an object of class InstrumentDao, and I want to add the color atribute, and it's respective getter and setter methods.

Then the question is, can I create at runtime a new dynamic class from the InstrumentDao, that has the new properties of guitar, created using reflection or something? (I accept suggestions of course)

Then I would use an abstract dao like this to get the work done:

https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics

The main problem is that I am not sure if Hibernate will accept any object created in this way. Old spring versions could do this with xml config files, but I also can not use it.

Thank you guys!





jeudi 28 octobre 2021

Detect RetentionPolicy.CLASS annotation in JUnit

It is likely there is not a solution, but I hope I am wrong.

I am writing a JUnit5 test to test some model classes. Some fields of the model classes are annotated by Lombok @NonNull which has CLASS level RetentionPolicy.

I want to make sure the Java model classes always comply with some constraints described by a schema. The schema defines which fields are required and which are not. In JUnit test, I want to make sure all fields that are required are annotated by Lombok @NonNull.

However, since the annotation is not a RUNTIME annotation, I do not have access to it in unit test.

Are there any workaround that can achieve my goal to automatically verify the constraint?





Best way to convert from one type to another at runtime [closed]

EDIT: Similar questions have been asked before, but this question is unique because the class I want to convert/cast to is not known until runtime, which means I can't have the name of the class to be cast/converted into written in the code.

I haven't found a way to convert the following class to a generic type using reflection. Below would be an example of the class I would like to convert to the type below it without having a switch statement or pre-defined mappings.

DTOClass
{
   Id;
   ShortName;
   LongName;
   TableName; //TableName = "EmployeeType"
}

EmployeeType
{
   Id;
   ShortName;
   LongName;
   TableName;
}

An example of some code that I have tried is below.

    public void Update<T>(T dtoClass) where T : DTOClass
    {
        var ConvertedEntity =  MagicConversionMethod(entity.TableName,dtoClass);
        MyOrmService.Update(ConvertedEntity)
    }

Any help would be appreciated.





C# How to make more clear Generic Methods

I am trying to make a generic method about executing custom commands in MVC base system.

I have a method called DispatchCommand. I give that method to command type and command parameter type. My command type inherited from a MVCCommand<T1>

public class CreateEnvironmentsCommand : MVCCommand<LevelVO>

My dispatch command method is like that,

IMVCCommand<T1> DispatchCommand<TCommand, T1>() where TCommand : IMVCCommand<T1>, new()

When I want to run this method I need to give CommandType and Command Generic Parameter Type for example:

DispatchCommand<CreateEnvironmentsCommand, LevelVO>();

But my command already included LevelVO type in itself. Is there a way to call this method like this:

DispatchCommand<CreateEnvironmentsCommand>();

Sorry for my english...





C# - Correct way to send a statement as a Func

I made a small benchmarking library that takes in Func<Task> objects, runs them a certain number of times and uses a Stopwatch object to figure out the average time it took to run:

public static async Task<BenchmarkResults> BenchmarkAsync(Func<Task> action, int repetitions, bool singleCore)
{
    // Run func, time it each time, compute average, return results.
}

I have made a small IBenchmark interface with a single Run() method. The way I am currently using this library is making benchmark classes that implement IBenchmark and passing a lambda that calls the Run method to it. Those IBenchmark objects are added to DI via an extension method:

var results = AsyncBenchmarker.BenchmarkAsync(async () => await benchmark.Run(), attribute.Repetitions, false).Result;

I would like to move away from needing this IBenchmark interface in the first place, it is getting in my way more than anything at this point. What I would like to do instead of passing benchmark.Run() in my lambda is pass a reflective invocation of another method in that same class. I tried something like this:

AsyncBenchmarker.BenchmarkAsync(async () => 
    await benchmark.GetType().GetMethod("SomeOtherMethod").Invoke(benchmark, null), attribute.Repetitions, false).Wait();

The problem is that Invoke returns a nullable object and I need this to be awaitable. How can I achieve this?





Getting field by name using reflect panics when checking IsZero

I have a piece of reflection code that attempts to get the field on a struct by name and then checks if the field exists:

type test struct {
   A bool
   B bool
}

t := new(test)
metaValue := reflect.ValueOf(t)
field := metaValue.FieldByName(name)
if field.IsZero() {
    glog.Errorf("Field %s was not on the struct", inner)
}

According to the documentation on FieldByName, this function should return a zero value if no field was found. However, the very next line panics with the error:

panic: reflect: call of reflect.Value.IsZero on zero Value

goroutine 268 [running]:
reflect.Value.IsZero({0x0, 0x0, 0x112a974})
        reflect/value.go:1475 +0x27f

According to this GitHub issue, this should only happen if the Value contains nil (i.e. no type) and IsValid should be used instead. Why is this happening?





mercredi 27 octobre 2021

Java reflection, is there an easy way to get field value by 'field path'?

I have a pretty complex class, like,

classA {
  public classB b;
}

classB {
  public classC c;
}

classC {
  public List<classD> d;
}
...

Now, given an instance of classA, and a field path like 'b.c.d.e.f.g', is there an easy way to get the target field value via reflection? Any existing library or something?

Many thanks.





mardi 26 octobre 2021

Using ServiceLoader to get All Instances of an Annotation

All!

I know that long questions are frowned upon, but this is the only way I will be able to get my problem adequately explained. So, I apologize up front for the length of this question.

I am working on a modular project that will be extensible via add-on modules. To that end, I am wanting to allow add-on modules to be able to provide their own menus, menu items and toolbar buttons. To accomplish this, I have created an API with some annotations in it. This API is located in a module called "Menu.API", and has the following classes defined:

@MenuProvider:

package com.my.menu.api;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.CLASS)
@Repeatable(RepeatableMenus.class)
public @interface MenuProvider {
    String name();
    String text();
    int position();
}

@RepeatableMenus:

package com.my.menu.api;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RepeatableMenus {
    MenuProvider[] value();
}

For the sake of brevity, we will only concentrate on this annotation, because I am sure the rest of them will work with whatever solution I am able to get for this one.

With this module completed, I created the module-info.java file with the following contents:

module Menu.API {
    requires java.base;   // Just for the sake of completeness.

    exports com.my.menu.api;
}

So, with the API in place, I created a second module called "Menu.Platform", with the following class defined:

package com.my.platform;

// Imports removed for brevity.

@MenuProvider(name = "fileMenu", text = "File", position = Integer.MIN_VALUE)
@MenuProvider(name = "editMenu", text = "Edit", position = Integer.MIN_VALUE + 1)
@MenuProvider(name = "toolsMenu", text = "Tools", position = Integer.MAX_VALUE - 1000)
@MenuProvider(name = "helpMenu", text = "Help", position = Integer.MAX_VALUE)
public class App {

    private final MainFrame mainFrame;
    private final JMenuBar menuBar;
    private final JToolBar toolBar;
    private final JPanel statusPanel;
    private final JLabel statusLabel;
    
    public static MenuProvider provider() {
        // I am not sure how to send back my @MenuProvider annotations.
    }

    public App() {
        configureWindowParts();
    }

    private void configureWindowParts() {
        // No problems here...
    }

    private void initialize(String[] args) {
        // I do not need the args[] variable yet.
        
        createMenuBar();
    
        // ... the rest of the initialization.
    }

    private void createMenuBar() {
        ServiceLoader<MenuProvider> menusLoader = ServiceLoader.load(MenuProvider.class);

        // PostionableMenu is a subclass of JMenu that implements Comparable and provides
        //+ the `position` parameter.
        List<PositionableMenu> menus = new ArrayList<>();

        for (MenuProvider p : menusLoader) {
            PositionableMenu menu = new PositionableMenu(p.name(), p.text(), p.position());
            menus.add(menu);
        }

        Collections.sort(menus);

        menus.foreach(m -> {
            menuBar.add(m);
        });
    }
}

module-info.java:

module Menu.Platform {
    requires java.desktop;
    requires Menu.API;

    uses com.my.menu.api.MenuProvider;
    uses com.my.menu.api.RepeatableMenus;

    export com.my.platform;

    provides com.my.menu.api.MenuProvider with com.my.platform.App;
}

So my problem is that I receive the error:

the service implementation type must be a subtype of the service interface type,
or have a public static no-args method named "provider" returning the service implementation

...when I do not have the public static MenuProvider provider() method in my App class. But then when I put that method in my App class, I have no clue how to return those four (4) @MenuProviders from the method.

Any assistance that can be given to point me in the right direction is greatly appreciated. Thank you all in advance!

-SC

[EDIT] Well, I spent so long thinking of just how to ask this question that the answer came to me shortly after posting it...

What needs to be returned from the provider method is obtained by reflecting on the class:

    public static MenuProvider provider(){
        MenuProvider[] provider = App.class.getAnnotationsByType(MenuProvider.class);
        
        // How to return an array? If I change the return type to an
        //+ array, I get errors again because the provider method only
        //+ wants to return a single instance.
    }

This was my conundrum now. So I was thinking about how to edit this question when the answer hit me like a ton of bricks! Instead of returning the MenuProvider, I needed to return the RepeatableMenus instance. The value property of RepeatableMenus returns an array of MenuProviders. DUH!

So, I updated the provider method as follows:

    public static RepeatableMenus provider(){
        RepeatableMenus provider = App.class.getAnnotation(RepeatableMenus.class);
        
        return provider;
    }

And, I changed my module-info.java file to this:

module Menu.Platform {
    requires java.desktop;
    requires Menu.API;

    uses com.my.menu.api.MenuProvider;
    uses com.my.menu.api.RepeatableMenus;

    export com.my.platform;

    provides com.my.menu.api.RepeatableMenus with com.my.platform.App;
}

Now, I am receiving all of the @MenuProvider instances from my class. I cannot wait to try it from an additional module...

Thank you all anyway for the possible help you would have offered.

-SC





Java (JPMS): Is it possbile to inherit reflective access to annonymous child module?

Lets say, I write a module/library named mylib that uses an internal/hidden third party module/library named internal. The API of mylib does not expose any functionality from that third party library and it may be replaced by something else in the near future.

module mylib {
    requires internal;
    exports some.pgk.from.mylib;
}

But here is my problem. The internal library needs reflective access to the classes/objects that are passed through the public API of mylib to do it's work.

An example application/module named app that utilizes my library would have to define the following moduleinfo.java

module app {
    requires mylib;
    opens some.pkg.from.app to internal;
}

But this is bad, because it exposes the internally used module to the users of my library, and I would not be able to remove/change it in the future without breaking app. Ideally i would like to allow the module internal reflective access to all modules that are open to mylib instead:

module app {
    requires mylib;
    opens some.pkg.from.app to mylib; // also open to internal without naming it
}

Can this be done with the current (Java 17) module system? Is there a good workaround in case this is not possible?





Finding Generic Type Parameter through reflection [duplicate]

I'm new to Reflection and Im just trying cool little ideas.

I'm trying to see if there is a way to find the type that a property is and pass it through a generic type parameter? If it's not possible that's ok, just would be fun to play around with, even if it's not that efficient

I have the field type, just need to have a way to convert it so it's acceptable by the compiler, unless generic type parameters need to be hard coded.

Here is an example of what I want to do:

foreach(FieldInfo f in typeof(ActivityData).GetFields())
{ 
    Database.GetData</*Do something here?*/>(nReader, "");
}

rtn.ActionID = Database.GetData<int>(nReader, GetAttribute<DBAttribute, ActivityData>(nameof(this.ActionID)).ColumnName);

So the last line is what I want to do, but for each field inside of my object, however, I'm not sure how to get the generic type parameter through reflection, or if its possible at all.





React Typescript: Reflection (listing properties of an interface)

im writing a node-based editor for neural-nets that (currently) uses tensorflow.js for the creation of the networks themself. Tensorflow.js has a layers api with diffrent factory-functions that each have an interface for their arguments. E.g.

interface DenseLayerArgs {
    units: number, 
    useBias?: boolean, 
    ...
}
const dense(args: DenseLayerArgs): {
...
}

My goal is to load all of those factory functions automaticly and create a menu for each thats based on the Args interface. Since its not possible to access properties that might be undefined in plain TS, the solution seems to be some kind of transformer library (eg. https://www.npmjs.com/package/ts-reflection ). But i havnt been able to get any custom transformer running with my create-react-app with typescript setup.

Has anyone been able to get React working with custom transformers or has some other solution for creating a menu from an interface ?

cheers





lundi 25 octobre 2021

How to get only class and IEnumerable from object using reflection in c#?

I need to get only class and IEnumerable from object which can be dynamic(not dynamic keyword in c#). I need to get all properties and their values from class using reflection where property type is class or implements IEnumerable interface. Any suggestions?

 public class Person
{
    public Person()
    {
        NestedPeople = new List<NestedPerson>();
    }
    public string Name { get; set; }
    public List<NestedPerson> NestedPeople { get; set; }
    public List<SomeClass> SomeClasses { get; set; }
    public Base Base { get; set; }
}

public class NestedPerson
{
    public string Name { get; set; }
}

public class Base
{
    public Guid Id { get; set; }
}

public class SomeClass
{
    public Guid Id { get; set; }
}

This is minimal sample code just to explain what I need. I need a method to retrieve properties from the passed object which are either type of class or implements IEnumerable interface. Expected method :

public IEnumerable<object> GetData(object obj)
{
  // need to get properties and values where property is class or implements 
  IEnumerable interface
 
}




Find all package level objects with scala 3 reflection

I'm trying to get a list of Expr[Any] that corresponds to all package level objects. I can find the package symbol itself (by chasing up the symbol owner of any top level object), then iterate through the declaredFields. I can find the top level object ValDef nodes this way, but there is no associated Term in the ValDef. I also can't use Term.select on the package tree to get the declared members because I can't get the tree of of a package symbol.

It seems like it should be possible to get the Term (and not just the ValDef) associated with these top level singleton objects from their symbols somehow, but I can't figure it out.

Basically I would like to do something like this:

inline def packageToucher[T](something : T) : List[Any] = {
    ${ packageToucherImpl('something) } 
}

def packageToucherImpl[T](something : Expr[T])(using Quotes, Type[T]): Expr[List[Any]] = {
    import quotes.reflect.*
    // assume something is a top level object
    val _package = TypeRepr.of[T].typeSymbol.owner 
    val fields = _package.declaredFields
    val packageExpr = _package.tree.asExpr //  assertion failed: Cannot get tree of package symbol
    val packageTree = packageExpr.asTerm
    val fieldExprs : List[Expr[Any]] = fields.map( f => packageTree.select(f).asExpr)

    Expr.ofList(fieldExprs)
}

and an example of usage would be:

// in actions.scala
package potato

object Actions // dummy object for finding package

object yelling extends Action("yell")

object sleeping extends Action("sleep")

object typing extends Action("type")

and in main:

import potato.*
val actions = Macros.packageToucher(Actions) // should be List(Actions, yelling, sleeping, typing)

Any help would be appreciated. I am a bit of a noob when it comes to scala 3 macros.

Thanks!





Read SQL Values with reflection and assign the correct datatype

Until now i got SQL-results from a datareader and stored it in a collection, all variables were strings:

                AdressEntries client = new AdressEntries();
                Type t = client.GetType();
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {

                                while (reader.Read())
                                {
                                    client = new AdressEntries();
                                    foreach (PropertyInfo variable in t.GetProperties())
                                    {
                                        variable.SetValue(client, reader[variable.Name].ToString());
                                    }
                                    allClients.Add(client);
                                }
                                reader.Close();

this worked great for all kind of collections. Now i want to use more datatypes in the app and in the SQL Database (like date, int, double etc.) The variables used in the collections are nullable (like int?, Boolean?, etc.).

Now i have to cast/convert the SQL-Results. I did this with a little correction to the above code with Convert.ChangeType:

 using (SqlDataReader reader = cmd.ExecuteReader())
                            {

                                while (reader.Read())
                                {
                                    client = new AdressEntries();
                                    foreach (PropertyInfo variable in t.GetProperties())
                                    {
                                        variable.SetValue(client, Convert.ChangeType(reader[variable.Name], variable.GetType()));
                                    }
                                    allClients.Add(client);
                                }
                                reader.Close();

Can I do this, or do I run into problems?





How to get all the fields and properties as well as values when catching exceptions

In addition to capturing an exception and logging it I am trying to get all the field and property names and values belonging to the class in which the exception was thrown. This data will then be logged and sent to me by my clients.

This information can be obtained within the catch block of the culprit method's try/catch using Reflection however how can I get the data specific to the class if the exception is not caught within that catch block.

I am catching all program wide exceptions at startup.





How To map List of Object inside object using Reflection

I searched for a solution to this problem, but I did not find a solution. Please help me.

I used the reflection to generate custom dynamic AutoMapper ,because I used library AutoMapper in .net core m but the performance is vary bad.

1. ClassesViewModel    

    public class ClassesViewModel 
         {
            public int ClassID {get;set;}
            public string ClassNames {get;set;}
            public List<StudedntViewModel > Studednts {get;set;}
         } 

 
    
    public Class StudedntViewModel 
    {
        public int StudedntID {get;set;}
        public int StudentName{get;set;}
    }


 2. ClassesDto

public class ClassesDto 
         {
            public int ClassID {get;set;}
            public string ClassNames {get;set;}
            public List<StudedntDto > Studednts {get;set;}
         }  
        
        public Class StudedntDto 
        {
            public int StudedntID {get;set;}
            public int StudentName{get;set;}
        }

now I need to mapping from ClassesViewmodel to ClassesDto , this below code i used to handle this cases.

        public static void MatchAndMap<TSource, TDestination>(this TSource source, TDestination destination)
where TSource : class, new()
where TDestination : class, new()
        {
            try
            {
                // source = ClasseViewModel
                // destination = ClassesDto
                if (source != null && destination != null)
                {
                    // Get All proprity from source (ClasseViewModel)
                    List<PropertyInfo> sourceProperties = source.GetType().GetProperties().ToList<PropertyInfo>();
                    // Get All proprity from source (ClasseViewDto)
                    List<PropertyInfo> destinationProperties = destination.GetType().GetProperties().ToList<PropertyInfo>();

                    foreach (PropertyInfo sourceProperty in sourceProperties)
                    {
                        // get the selected proprity  from destinationProperties(ClasseViewDto) based sourceProperty selected.
                        // in this line i have problem , the object StudentDto in destination is null 
                        PropertyInfo destinationProperty = destinationProperties.Find(item => item.Name == sourceProperty.Name);
                        var getMethod = sourceProperty.GetGetMethod();
                        // check if proprity is Collection
                        if (sourceProperty.PropertyType.Namespace.Contains("Collections"))
                        {
                            // get All data from object StudentViewModel
                            var arrayObject = getMethod.Invoke(source, null);

                            foreach (object element in (IEnumerable)arrayObject)
                            {
                                // Get All proprity from Student source (StudentViewModel)
                                List<PropertyInfo> SubSourcePropertiesByElement = element.GetType().GetProperties().ToList<PropertyInfo>();

                                foreach (PropertyInfo arrayObjPinfo in SubSourcePropertiesByElement)
                                {
                                    // here the problem  how can  assign value from object destinationProperty if the proprity "destinationProperty" is null
                                    destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null);
                                }
                            }
                        }
                        // this block if sourceProperty is not Collection 
                        else
                        {
                            if (destinationProperty != null)
                            {
                                try
                                {
                                    destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null);
                                }
                                catch (Exception ex)
                                {

                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }

I hope the problem is clear to everyone, thank you in advance.





How to call Kotlin companion object function using reflection and interface

Assume I have the following interface:

interface Fooable {
    fun foo()
}

The interface is implemented by named companion objects; for example:

class Impl1 {
    companion object Foo : Fooable {
        fun foo() { ... }
    }
}

class Impl2 {
    companion object Foo : Fooable {
        fun foo() { ... }
    }
}

I want to be able to map the name of each Impl class to a Fooable instance (since companion objects are always singleton instances); for example:

fun mapImplToFooable(): Map<String, Fooable> = mapOf(
    "Impl1" to Impl1.Foo,
    "Impl2" to Impl2.Foo
)

I could then call this; for example:

val map = mapImplToFooable()
map["Impl1"]!!.foo()

What I want is to be able to create the map using reflection, rather than hard coding it, assuming convention being that every Impl has a companion object Foo : Fooable { ... }

What I have so far is a function which is able to find all classes in a package, and sub-packages:

fun findAllClasses(): List<Class<*>> { ... }

And from that, I managed to get this far:

function mapImplToFooable(): Map<String, Fooable> {
    return findAllClasses()
        .filter { Fooable::class.java.isAssignableFrom(it) }
        .map { clazz -> it.name to clazz } // This is a problem...
        .toMap()

The problem is that clazz is a Class<Fooable> rather than an instance of Fooable (in each case, the companion object).

How do I obtain the companion object instance, rather than just a Class<Fooable>?





dimanche 24 octobre 2021

How to get properties of a class which are IEnumerable of a class or an IEnumerable of a class inherited from that class [duplicate]

In c# I have a class with properties on it which returns IEnumerables.

public class MyClass
{
   public IEnumerable<MyPropClass1> Prop1 { get { return _prop1; } }
   public IEnumerable<MyPropClass2> Prop2 { get { return _prop2; } }
   public IEnumerable<AnotherClassAltogether> Prop3 {get {return _prop3; } }
   ...
}

Lets say MyPropClass1 and MyPropClass2 both inherit from MyPropBaseClass but AnotherClassAltogether doesn't.

What is the simplest way to get all properties from MyClass which either are an IEnumerable of a certain class, or an IEnumerable of a class which is somewhere down the chain is inherited from that class?

E.g. if I wanted to query MyClass for properties based on IEnumerables templated to something that is based on MyPropBaseClass then it should return Prop1 and Prop2

For more clarity (hopefully to address the close vote) a pseudo function to answer this question would be something like:

var properties = GetIEnumerablePropertiesOfType(typeof(MyClass), typeof(MyPropBaseClass))

and this would return a list of properties containing Prop1 and Prop2 (as an enumerable of System.Reflection.PropertyInfo)





How to get all properties of a class where the property is based on a certain type

In c# I have a class with properties on it.

public class MyClass
{
   public MyPropClass1 Prop1 { get; set; }
   public MyPropClass2 Prop2 { get; set; }
   public AnotherClassAltogether Prop3 {get; set; }
}

Lets say MyPropClass1 and MyPropClass2 both inherit from MyPropBaseClass but AnotherClassAltogether doesn't.

What is the simplest way to get all properties from MyClass which either are, or somewhere down the chain are inherited from, a class?

E.g. if I wanted to query MyClass for properties based on MyPropBaseClass then it should return Prop1 and Prop2





Jackson typeRefernce with dynamic method parameter type

I want to be able to create Jackson typeRefernce with dynamic method parameter type with below example using reflection method.getParameterTypes()[1].

Since TypeRefernce only takes compile type parameters but I heard you can do some trick also to work with dynamic types.

 Method method = methodsMap.getOrDefault("createXXX".toLowerCase(), null);

        if(method != null && myBean!= null){
       
               Object retval  = method.invoke(myBean, mapper.convertValue(product , new TypeReference<method.getParameterTypes()[1]>(){}));
        }




Check if class contains / is part of another parent class

I would like to check whether a class is a subclass (note: Not correct term! I am not talking about inheritance, but rather about a class being a member of another class) with regard to the implementation.

Example

@NoArgsConstructor
@AllArgsConstructor
public class Car  {

    private String id;
    private String brand;
    private Vehicle vehicle;
}

@NoArgsConstructor
@AllArgsConstructor
public class Vehicle{

    private String id;
    private String brand;
    private Rims rims;
}

@NoArgsConstructor
@AllArgsConstructor
public class Rims {

    private String id;
    private String brand;
}

You can see here three classes with an association (A car has a vehicle, a vehicle has a rim..)

Let's assume that I can extract a Rim with properties

Car car = new Car(123, "Mercedes", 4)  *id=123, brand="mercedes", rims=4*
Vehicle vehicle = new Vehicle(123, 'michellin', 4)
Rims rims = new Rims(333, 'amg')

Now I want to check whether the rims with the id of '333' is a subclass of car with the id of 123 => This is why I talked about is subclass of the implementation .

Is there a way to do this? instanceOf and isAssignable do not work.

id: 123 and brand: michellin, and I want to check whether it's a subclass.





samedi 23 octobre 2021

Why does MethodByName().Call() return "[

I have the following interface

import (
    "fmt"
    "reflect"
)

type geometry interface {
    Area() float64
    Perimeter() float64
}

func prettyPrint(geometry geometry) {
    geometryType := reflect.TypeOf(geometry)
    fmt.Println(geometryType.Name())
    fmt.Printf("\t%+v\n", geometry)

    for i := 0; i < geometryType.NumMethod(); i++ {
        method := geometryType.Method(i)
        fmt.Println(method.Name)
        fmt.Println(reflect.ValueOf(geometry).MethodByName(method.Name).Call(nil))
    }
}

When calling prettyPrint using a type which implements geometry:

func main() {
    circle := circle{radius: 5}
    prettyPrint(circle)
}

This is the output

circle
        {radius:5}
Area
[<float64 Value>]
Perimeter
[<float64 Value>]

I don't quite understand the reflect.Call() method, or why its printing out each value as [<float64 Value>] - I am trying to get the resulting output from calling the func on the passed in geometry type

I've tried passing in []reflect.Value{} instead of nil as suggested in various places online, but it gives the same results as above

Can anyone shed some light on what exactly is going on here?


I also tried this Invoke method from elsewhere on SO

func Invoke(any interface{}, name string, args ...interface{}) {
    inputs := make([]reflect.Value, len(args))
    for i, _ := range args {
        inputs[i] = reflect.ValueOf(args[i])
    }
    fmt.Println(reflect.ValueOf(any).MethodByName(name).Call(inputs))
}

It gives the same results..

Invoke(circle{}, "Area")

outputs

[<float64 Value>]




Why does type.NumMethod() return 0?

I have this interface

type geometry interface {
    area() float64
    perimeter() float64
}

implemented by circle

import "math"

type circle struct {
    radius float64
}

func (circle circle) area() float64 {
    return math.Pi * circle.radius
}

func (circle circle) perimeter() float64 {
    return 2 * math.Pi * circle.radius
}

but when I pass an instance of circle to my prettyPrint function, NumMethod() returns 0 - why doesn't it count area() and perimeter?

func prettyPrent(geometry geometry) {
    geometryType := reflect.TypeOf(geometry)
    fmt.Println(geometryType.Name())
    fmt.Printf("\t%+v\n", geometry)

    // This prints 0 
    fmt.Println(geometryType.NumMethod())

    for i := 0; i < geometryType.NumMethod(); i++ {
        method := geometryType.Method(i)
        fmt.Println(method.Name)
    }
}

in main func:

circle := circle{radius: 4}
prettyPrint(circle)




Modify Java Random with reflection [duplicate]

Java reflection is powerful, I know it can SET declared fields or invoke method with new parameters.
Now can we "hack" the Random class like below to be "true" everytime?
System.out.println( java.lang.Math.random() == java.lang.Math.random() );

Math.random()

    public static double random() {
        return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();}

And the nextDouble()

     public double nextDouble() {
        return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;}

And I'm stuck here, these methods don't even use any parameter to tamper with and I don't know if Java reflection can mess around inside method. Is there anyway else to get the same Math.random() every time?





How to get interface extending another one (aka super) by its super

Here is my code using Guava:

public interface NetSession {
    void connect();
}

public interface HttpSession extends NetSession {
    void useRestApi();
}

class HttpSessionImpl implements HttpSession {
}

class Test {
    NetSession makeProxy(NetSession session) {
        TypeToken<? extends NetSession> sessionTT = TypeToken.of(session.getClass());
        TypeToken<? extends NetSession>.TypeSet ifaces = sessionTT.getTypes().interfaces();
        //  here we looking for real <? extends NetSession> interface
        Class<? extends NetSession> sessionIface = (Class<? extends NetSession>) ifaces.stream()
                .filter(i -> i.isSubtypeOf(NetSession.class))
                .map(i -> i.getRawType())
                .findAny().orElse(null);
        assert sessionIface != null;
        
        session.connect();
        if (sessionIface == NetSession.class) {
            return session; // as is
        }
        // make extra
        HttpSession httpSession = (HttpSession) session;
        httpSession.useRestApi();
    }
}

My question is: is there more elegant way to find Class of interface by its super? i mean something like:

Class<? extends NetSession> sessionIface = sessionTT.getInterfaceExtending(NetSession.class);
assert sessionIface == HttpSession.class; // is ok in case above

With Guava or else make no difference.





vendredi 22 octobre 2021

Finding a property name within a lambda expression

I have a coding problem to solve, I kind of know the path I should be following, but there is still something missing. I got a mission to change a code to make it more generic and reduce the redundance.

The whole class is given below. It seems a bit dummy, the question is the redundance itself.

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

namespace TestRedundance
{
    public class EntityRedundance
    {
        public class Entity
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public DateTime ValidFrom { get; set; }
        }

        private void AddSorting(IQueryable<Entity> query, List<string> sortingColumns, bool orderDescending)
        {

            if (!sortingColumns.Any())
            {
                query = query.OrderBy(x => x.Name);
                return;
            }

            foreach (var column in sortingColumns)
            {

                switch (column)
                {

                    case "Name":
                        query = orderDescending ? query.OrderByDescending(x => x.Name) : query.OrderBy(x => x.Name);
                        break;
                    case "Description":
                        query = orderDescending ? query.OrderByDescending(x => x.Description) : query.OrderBy(x => x.Description);
                        break;
                    case "ValidFrom":
                        query = orderDescending ? query.OrderByDescending(x => x.ValidFrom) : query.OrderBy(x => x.ValidFrom);
                        break;

                }
            }
        }
    }
}

As far as I understood, the redundance is on repeting the same exact code in each switch case condition, changing only the column to be sorted by.

My intention was to change it to a single line, comparing the property name of my entity with the column name, using Reflection, and then replacing the switch-case block for this single line. But the lambda expression does not allow me to do that. Something like the line below, which is commented because it's sintax is wrong.

//query = orderDescending ? query.OrderByDescending(x => 
//x.GetType().GetProperties() : query.OrderBy(x => x.Name);

I would appreciate any suggestions.

Many thanks.





How to get all Guid properties and their values with the name "Id" from class?

I have a class which has nested objects. I wanna get all the Guid properties and their values with the name "Id". This is simple version of my classes:

public class Main
{
    public Guid Id { get; set; }

    public ICollection<Child> Children { get; set; }
}

public class Child
{
    public Guid Id { get; set; }
    public ICollection<GrandChild> GrandChildren { get; set; }
}

public class GrandChild
{
    public Guid Id { get; set; }
}

I am gonna have Main class object and wanna retrieve all Guid properties with their values for all nested and etc. for further logic. Any suggestions?





Dereference eventual pointers in an empty interface array [duplicate]

I have an array of interface{}, and some of the elements may be pointers. I want to "flatten" the array such that no element is a pointer, so I want to dereference eventual pointers. Essentially I want to do something like that :

maybePointers := []interface{}{}
noPointers := []interface{}{}
var val interface{}
for _,v := range maybePointers {
    
    // if v is a pointer, dereference it
    reflectVal := reflect.ValueOf(v)
    if reflectVal.Kind() == reflect.Ptr {
        v = *v.(*interface{})
    }
    noPointers = append(noPointers, v)
}

But with this code, I get interface conversion: interface {} is *int64, not *interface {}





Reflection vs. finding child view

For the same reason described in this SO question, I want to get access to the RecyclerView inside a ViewPager2. This RecyclerView is not exposed in any way.

I kept the title deliberately broad, because my intention of this question is not to solve a specific question; the problem is solved. The ViewPager2 is mere an example. I want to know if there is an objective better long term approach.

One could:

  • Use reflection to access the property mRecyclerView
  • Find and cast a view child to RecyclerView.
  • (Do not use ViewPager2, but use an RecyclerView and add a layout manager, snapping and paging manually; deemed out of scope for this question)

I'd say:

  • The RV is fetched once, so cost is negligible
  • ViewPager2 is stable enough, that at least the name of the property or the amount of child views will not change.
  • Both solutions hardcode knowledge of ViewPager2 in the app it should now know

In this case, is one better than the other?





With Json.NET, how can I merge two C# objects that need to be serialized together?

Say I have some classes that I often serialize normally, such as

public class A
{
    public A(int x, bool y)
    {
        X = x;
        Y = y;
    }

    [JsonProperty("x_thing")]
    public int X { get; }

    [JsonProperty("y_thing")]
    public bool Y { get; }
}

public class B
{
    public B(string s)
    {
        S = s;
    }

    [JsonProperty("string_thing")]
    public string S { get; }
}

If I want to start here (but pretend A and B are arbitrary objects):

var obj1 = new A(4, true);
var obj2 = new B("hello world");

... then how can I idiomatically produce this JSON serialization?

{
    "x_thing": 4,
    "y_thing": true,
    "string_thing": "hello world"
}




How to check if interface is a a pointer to a slice

I know how to check if an interface is a pointer:

func isPointerArray(i interface{}) bool {
    if i == nil {
        return false
    }
    if reflect.ValueOf(i).Kind() != reflect.Ptr {
        return false
    }
}

But how can I check if that pointer is a slice? TypeOf is a pointer.





Obtain KClass<*> property from Annotation using Kotlin Reflection

I have an annotation

// declaration 
annotation class MyAnnotation(val name: String, val type: KClass<*>)

// usage
@MyAnnotation(name = "name", type = String::class)
fun someFuncion()

What I'm trying to achieve is to obtain properties of my annotation using reflection (done in Annotation Processor)

So far I have managed to get the name property using this extension:

private inline fun <reified T> Any.fieldByName(name: String): T {
    try {
        return this::class.members.find { it.name == name }?.call(this) as T
    } catch (e: Exception) {
        throw IllegalArgumentException("Error process $name member: ${e.stackTraceToString()}")
    }
}

But when it comes process the type parameter I get java.lang.reflect.InvocationTargetException

What I hope to get is an instance of KClass<*> so I can do some logic later on, depending on the type.

Is there even a way to achieve that? Or why is there this error and how should I handle that scenario.

I also tried

  • javaClass.kotlin.memberProperties - same result

Thanks in Advance





Handle generic types in GetMethod

What would be the correct arguments for GetMethod in the AddService(services, type, instance) exactly defining the generic version (just in case there will come more overloads).

I know I could just keep the method names different but I don't want to.

Currently I get either null or an exception due to multiple found method versions...

The code:

namespace Sample
{

    public interface IService { }

    public static class SampleExtensions
    {

        public static IServiceCollection AddService<T>(this IServiceCollection services, T instance) where T : IService
        {
            //services.AddSingleton<T>(instance);
            services.AddSingleton(instance.GetType(), instance); // register with the concrete implementation type
            //some stuff that only works with generic T
            return services;
        }

        public static IServiceCollection AddService(this IServiceCollection services, Type type, object instance)
        {

            Type classType = typeof(SampleExtensions);
            MethodInfo methodInfo = classType.GetMethod                         // correct arguments??
            (
                nameof(AddService),                                             // only name would bring 2 results
                new Type[] { typeof(IServiceCollection), typeof(object) }       // ??? instance is generic
            );
            MethodInfo genericMethod = methodInfo.MakeGenericMethod(type);
            genericMethod.Invoke(null, new[] { services, instance });           // call the generic method version
            return services;
        }

    }
}




jeudi 21 octobre 2021

Nodejs function - print properties of a class using reflection

I need help with writing a javascript function that gets a class as a parameter, and prints all its public properties (name and value) using reflection with indentation.

Some properties can be of type class so the properties need to be printed with the correct indentation.

Example:

Class A {
  a1;
  a2;

  constructor() {
    this.a1 = 'a';
    this.a2 = 2;
  }
}


Class B {
  b1;
  b2;

  constructor() {
    this.b1 = true;
    this.b2 = new A();
  }
}

When getting class B as a parameter the output should be:

{
  b1: true,
  b2: {
    a1: a,
    a2: 2
  }
{

Thank you!





Java Spring Hibernate and Reflection

I have 5 tables in MySQL (words_1, words_2... words_5) with the same fields (id,words,sinonim). In the field "words" I put different count of words (for words_1 = 1 word, for words_5 = 5 words). I create 5 classes and Repo for those. Constructors and methods are the same.

import javax.persistence.*;

@Entity
@Table(name = "words_2")
public class Words2 {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String word;
    private String sinonim;

    public Words2() {
    }

    public Words2(String word, String sinonim) {
        this.word = word;
        this.sinonim = sinonim;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public String getSinonim() {
        return sinonim;
    }

    public void setSinonim(String sinonim) {
        this.sinonim = sinonim;
    }
}

How I can take my classes fields and methods, using variable(int = 1..5) with Reflection, for Class and same Repo identification?





mercredi 20 octobre 2021

Go - Failing escape analysis on different slice headers with shared data

I'm working on a project where I frequently convert []int32 to []byte. I created a function intsToBytes to perform an inplace conversion to minimize copying. I noticed that Go's escape analysis doesn't realize that ints and bytes reference the same underlying data. As a result, ints is overwritten by the next function's stack data and bytes lives on and references the overwritten data.

The only solution I can think of involves copying the data into a new byte slice. Is there away to avoid copying the data?

func pack() []byte {
   ints := []int32{1,2,3,4,5} // This does not escape so it is allocated on the stack
   bytes := intsToBytes(ints) // 'ints' and 'bytes' are different slice headers
   return bytes 
   // After the return, the []int32{...} is deallocated and can be overwritten
   // by the next function's stack data
}

func intsToBytes(i []int32) []byte {
    const SizeOfInt32 = 4

    // Get the slice header
    header := *(*reflect.SliceHeader)(unsafe.Pointer(&i))
    header.Len *= SizeOfInt32
    header.Cap *= SizeOfInt32

    // Convert slice header to an []byte
    data := *(*[]byte)(unsafe.Pointer(&header))

    /* Potentital Solution
    outData := make([]byte, len(data))
    copy(outData, data)
    return outData
    */

    return data
}






Recursively get private field value using reflection

I've got a deeply nested private fields chain which I'd like to iterate recursively to get the value of some target field.

How can this be done?

For example:

public class A
{
   private B b;
   public A(B b) { this.b = b; }
}

public class B
{
   private C[] cItems;
   public B(C[] cItems) { this.cItems = cItems; }
}

public class C
{
   private string target; // <-- get this value
   public C(int target) { this.target = val; }
}
public static void GetFieldValueByPath(object targetObj, string targetFieldPath)
{
   // how to do it?
}

Usage will be:

public void DoSomething(A a)
{
   var val = GetFieldValueByPath(a, "b.cItems[2].target");
}
  • Notes:
    • There is a related question about recursively getting properties, but not fields. But even then, it doesn't support array fields.
    • Related questions such as this one for getting fields are not recursive.




Nuget Library to get all types that implement an interface in all assemblies and referenced assemblies

I am struggling to find a good answer on this.

I need to scan all the classes that implement an interface IDomainEvent.

The problem is that those types are in projects that are not necessarily loaded. For example, if my main assembly is WebApi, there is a dependency on Application, which depends on Domain, which depends on DomainEvents

therefore, I don't have an "easy" way to get all the types that implement IDomainEvent and are in *DomainEvents.csproj projects

Is there any nuget library that can dynamically navigate through all referenced projects/assemblies and its subdependencies and is able to retrieve all types implementing an interface?

It happens at startup once, so I'm not too concerned about performance.

PS: The following method returns 0, as expected, because the assemblies are not loaded

var allDomainEventTypes =
  AppDomain
    .CurrentDomain
    .GetAssemblies()
    .SelectMany(x => x.GetTypes())
    .Where(t => t.IsAssignableTo(typeof(IDomainEvent)) && !t.IsInterface)
    .ToList();




Introspect referenced type of an annotated class

I'm developing an annotation processor aiming to generate code by introspecting annotated class return types methods. I have 2 modules:

  • app: containing my annotated classes
  • processor: containing my annotation and the relative processor

These are my gradle files:

app/build.gradle

plugins {
    id 'java'
}

dependencies {

    testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'

    implementation project(':processor')
    annotationProcessor project(':processor')
}

compileJava {
    options.annotationProcessorPath = configurations.annotationProcessor
}

processor/build.gradle

plugins {
    id 'java-library'
}

repositories {
    mavenCentral()
}

dependencies {

    testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'
}

settings.gradle

rootProject.name = 'MyProject'
include('app')
include('processor')

I have this annotation (processor module)

@Target(ElementType.TYPE)
public @interface MyAnnotation {

}

This is an annotated class

@MyAnnotation
public class DogGenerator {

    public Dog getDog() {
        return new Dog("Brutus");
    }
}

This is my processor

@SupportedSourceVersion(SourceVersion.RELEASE_11)
@SupportedAnnotationTypes("com.myann.MyAnnotation")
public class MyAnnotationProcessor extends AbstractProcessor {

    private Filer filer;
    private Messager messager;
    private Elements elementUtils;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        filer = processingEnv.getFiler();
        messager = processingEnv.getMessager();
        elementUtils = processingEnv.getElementUtils();
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        final Set<? extends Element> elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(
                MyAnnotation.class);

        for (Element annotatedElement : elementsAnnotatedWith) {
            if (annotatedElement.getKind() != ElementKind.CLASS) {

                messager.printMessage(Kind.ERROR, "Only classes and method can be annotated with " + MyAnnotation.class.getSimpleName(), annotatedElement);
                return false;
            }

            TypeElement typeEl = elementUtils.getTypeElement(annotatedElement.asType().toString());
            final Element method = typeEl.getEnclosedElements()
                    .stream()
                    .filter(o -> o.getKind() == ElementKind.METHOD)
                    .findFirst()
                    .get();

            TypeMirror returnType = ((ExecutableElement)method).getReturnType();
            messager.printMessage(Kind.WARNING,"return type " + returnType.toString());

        }

        return false;
    }
}

With this code I'm able to print the return type com.myann.Dog, but how can I introspect it in order to get its fields or methods?

If I try to load the class with Class.forName, I receive a ClassNotFoundException. If I add app module as a dependency of the processor module I hit a circular dependency error.





j2objc reflection support in native iOS classes

I've just updated my j2objc tool from 1.0.2 to 2.8. As far as I know there were changes in reflection starting from 1.1 version. And now code doesn't work anymore.

We have IApplicationSupport.java interface. Something like this:

public interface IApplicationSupport
{
    void openSupport();
}

This code is successfully translated to Objective-С with j2objc

Then we have platform dependent classes AndroidApplicationSupport and IosApplicationSupport that are not translated. Android part is ok, but iOS has some problems.

Somewhere in code later I need to call [IOSClass classForIosName:@"IosApplicationSupport"]. And that's the problem. I get the next exception every time com.google.j2objc.ReflectionStrippedError: IosApplicationSupport: Reflection is unavailable. Fix this by avoiding reflection or building without --strip-reflection. Of course I do not use --strip-reflection flag during translation (but I believe the problem is not there). Avoid reflection seems to be extremely hard in my case, because there are too much classes with reflection is used.

I understand, that translated classes has rather big __metadata method. Is there any way to emulate metadata for native classes to enable reflection support? If I have to add metadata, are there any rules about how is this generated? Our project is heavy depends on it.

Thanks for any help!





C# - Converting list of property paths along with their values into Class object dynamically

For demonstrating my problem, let's consider there are 3 entities:

    public class Employee
    {
        public string Name { get; set; }
        public Department Department { get; set; }
        public Address Address { get; set; }
    }
    public class Department
    {
        public string Id { get; set; }

        public string Name { get; set; }
    }
    public class Address
    {
        public string City { get; set; }

        public string State { get; set; }

        public string ZipCode { get; set; }
    }

And there are list of property paths along with their values:

[{
    { "Deparment.Name", "IT" },
    { "Address.City", "SomeCity" }
}]

Finally I would like to generate the employee object using these list of key value pairs. To demonstrate my problem, I've used a very simple "Employee" entity here. However, I need to convert 100s of such key value pairs into one complex object & so I'm not considering option to mapping each property manually.

Provided all the properties in this complex entity are string properties. How can we achieve this dynamically.

I've tried to solve it by looping each property path & setting the property value dynamically in below manner using c# reflection :

(Inspired from https://stackoverflow.com/a/12294308/8588207)

private void SetProperty(string compoundProperty, object target, object value)
        {
            string[] bits = compoundProperty.Split('.');
            PropertyInfo propertyToSet = null;
            Type objectType = null;
            object tempObject = null;
            for (int i = 0; i < bits.Length - 1; i++)
            {
                if (tempObject == null)
                    tempObject = target;

                propertyToSet = tempObject.GetType().GetProperty(bits[i]);
                objectType = propertyToSet.PropertyType;
                tempObject = propertyToSet.GetValue(tempObject, null);
                if (tempObject == null && objectType != null)
                {
                    tempObject = Activator.CreateInstance(objectType);
                }
            }
            propertyToSet = tempObject.GetType().GetProperty(bits.Last());
            if (propertyToSet != null && propertyToSet.CanWrite)
                propertyToSet.SetValue(target, value, null);
        }




mardi 19 octobre 2021

Generate identity fingerprint of objects

To implement a caching mechanism in a SpringBoot application, I need to generate a collision free kind of identity fingerprint of objects of certain classes. This fingerprint shall not include all class attributes, because some of them need to be intentionally kept out from calculation because they do not describe the identity of the instance in point of view of the caching. As hashing algorithm, I selected sha-256.

The question, which concerns me, is not about the hashing algorithm itself but rather how to make sure that attributes, which are added later to the class (even in nested referenced classes) are not forgot to either intentionally include or exclude in the hash calculation. Currently, in the first MVP approach, I added methods (String identityHash() {...}) to the related classes, which contains hardcoded attribute value concatenations, which are hashed then.

However, I would rather like an Annotation based approach: Each attribute of the related classes shall have Annotations, which express, whether to include the attribute value in the hash calculation or not.

public class MyEntity {

    @IdentityHash(include=false)
    String id

    @IdentityHash(include=true)
    String attribute1

    @IdentityHash(include=true)
    MySubEntity subEntity
}

public class MySubEntity {

    @IdentityHash(include=false)
    String id

    @IdentityHash(include=true)
    Set<String> setOfValues
}

Rather than having identityHash methods on the classes, I could implement a Service, which calculates the corresponding hashes. But here I'am not sure about which is the correct way to go. One option would be: use reflection (e.g. BeanUtils, PropertyUtils) to enumerate the attributes (recursively!), build the hash input by concatenating their value representatives (e.g. Sets need to be sorted first...) Would reflection be OK in such an use case? Are there other possibilities? I imagine something like ObjectMapper, which either builds a String (or byte[]) representation to calculate the hash then...





ReflectionNamedType - how to RELIABLY obtain corresponding ReflectionClass?

HAVE:

  • An instance of ReflectionNamedType.

NEED a technique that will enable me to:

  • Reliably create an instance of ReflectionClass object for the type represented by the ReflectionNamedType object IF AND ONLY IF the type is actually a class type, i.e. the ReflectionClass constructor with that type name would succeed (barring autoload failure).

  • Reliably not crash or throw otherwise.

CONSTRAINED BY the following additional requirement:

  • The implementation MUST NOT use a hardcoded list of edge case type names. Everything must be pure reflection.
  • The implementation MUST NOT use the deprecated ->getClass() method.
  • The implementation MUST NOT rely on catching ReflectionException from the ReflectionClass constructor in order to determine that the type is not a class type.

Is this currently doable, or must some constraints be relaxed?





Accessing method on private Map member in Java

I got this private member private Map<Character, String> eTM = new HashMap<>();.

I need to be able read its size from a test. I'd like to do it using Java reflection, however it seems that in order to be able to call size() I'd have to get the field as a java.lang.reflect.Field. You can't call any Map methods on that so I'd have to cast the field to "Map<Character, String>" or "HashMap<Character, String>". That doesn't seem to be possible though.

I experimented a bit to see if you could somehow access the size method on a private Map, but I don't see a way to do this. For example:

Field eTmF = Holder.class.getDeclaredField("eTM");
HashMap castTM = (HashMap<String, Character>) eTmF; //cannot cast
castTM.size();//not available

This shows zero length: Holder.class.getDeclaredClasses().length;

and unsurprisingly this has nothing to print:

Class<?>[] classes = Holder.class.getDeclaredClasses();
Arrays.stream(classes).forEach(c -> System.out.println(c.getSimpleName()));

Is this simply as far as reflection goes or is there a way?

For now I've loosened the field to "protected", but if it's possible I'd like to learn. For one thing I was hoping for hints on reflection libraries that may be able to go deeper.





How do Spring repositories instantiate results from query methods?

Assume the following (jdbc) repository:

interface Repo : CrudRepository<MyType, Long> {
    @Query("select * from blabla")
    fun abc(): List<MyType>
}

Both for the method abc() and the methods included from the parent interface the auto generated runtime implementation of the Repo interface knows how to serialise result sets into instances of MyType subject to certain restrictions.

How does Spring have access to the type information from the generic parameter at runtime? How does it manage to create lists of the correct runtime types based solely on the type information provided in the interface?

My understanding is that I would not have sufficient information from a signature like mapV1() below to instantiate my result, and therefore I would need to introduce a second parameter with type Class<T> as shown in mapV2():

class Mapper {
   fun <T> mapV1(source: Any): T {
       /* 
       try to instantiate a result 
       of type T reflectively
       */
   }
   fun <T> mapV2(source: Any, klass: Class<T>): T {
       /* 
       try to instantiate a result 
       of type T reflectively
       */
   }
}

Somehow Spring avoids this problem.





Add Lombok annotations dynamically using Javassist

For a project I was experimenting javassist (java binary code manipulation library).

I was able to create a simple POJO class using below code

public static Class<?> createClass(ModelClass clazz) throws NotFoundException, CannotCompileException {
    ModelProperty[] properties = clazz.getProperties();

    ClassPool classPool = ClassPool.getDefault();
    CtClass ctClass = classPool.makeClass(clazz.getName());

    // add annotation
    ClassFile classFile = ctClass.getClassFile();
    ConstPool constpool = classFile.getConstPool();
    AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
    System.out.println(Data.class.getName());
    Annotation annotation = new Annotation(lombok.Data.class.getName(), constpool);
    Annotation annotation1 = new Annotation(Component.class.getName(), constpool);
    Annotation annotation2 = new Annotation(Deprecated.class.getName(), constpool);
    annotationsAttribute.setAnnotations(new Annotation[] {annotation, annotation1, annotation2});
    ctClass.getClassFile().addAttribute(annotationsAttribute);

    for (ModelProperty property : properties) {
        String camelCaseField = property.getName().substring(0, 1).toUpperCase() + property.getName().substring(1);
        CtField ctField = new CtField(resolveCtClass(property.getType()), property.getName(), ctClass);
        ctClass.addField(ctField);

        // add getter
        // CtMethod fieldGetter = CtNewMethod.getter("get" + camelCaseField, ctField);
        // ctClass.addMethod(fieldGetter);

        // add setter
        // CtMethod fieldSetter = CtNewMethod.setter("set" + camelCaseField, ctField);
        // ctClass.addMethod(fieldSetter);
    }

    return ctClass.toClass();
}

// ModelClass
@Data
public class ModelClass {

    private String name;

    private ModelProperty[] properties;

    public void setName(String name) {
        this.name = name;
    }

    public void setModelProperty(ModelProperty[] properties) {
        this.properties = properties;
    }

}

// ModelProperty
@Data
public class ModelProperty {

    private String name;

    private Class<?> type;

    public void setType(String type) {
        switch (type.toLowerCase()) {
            case "int":
            case "integer":
                this.type = Integer.class;
                break;
            case "float":
                this.type = Float.class;
                break;
            case "str":
            case "string":
                this.type = String.class;
                break;
            case "bool":
            case "boolean":
                this.type = Boolean.class;
                break;
            default:
                this.type = String.class;
                break;
        }
    }
}

I was able to create class by using createClass method. While inspecting class with Reflection API, I've noticed that lombok.Data annotation is not adding to class.

Class<?> clazz = PojoCreator.createClass(modelClassPerson);

for (final Method method : clazz.getMethods()) {
    System.out.println(method);
}
for (final Annotation annotation : clazz.getAnnotations()) {
    System.out.println(annotation);
}
for (final Method method : clazz.getDeclaredMethods()) {
    System.out.println(method);
}
for (final Annotation annotation : clazz.getDeclaredAnnotations()) {
    System.out.println(annotation);
}

Output

public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
@org.springframework.stereotype.Component(value="")
@java.lang.Deprecated(forRemoval=false, since="")
@org.springframework.stereotype.Component(value="")
@java.lang.Deprecated(forRemoval=false, since="")

As you can see from the output spring.Component and javalang.Deprecated is added but lombok.Data didn't.

pom.xml

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <!-- <scope>annotationProcessor</scope> -->
</dependency>

Tried setting scope as compile, runtime, provided but none seems to work.

Using mvn spring-boot:run to execute in command line

Where did I go wrong?

Thanks.





lundi 18 octobre 2021

How to dynamically map based on the field name using Auto mapper and Reflection

I have around 50 types having the same problem. The source has a (fieldName)specified field and depending on the value of the (fieldName)specified, I want to set the value for the field. So basically, if source (fieldName)Specified == true, then I want to set source fieldName value to destination fieldName. FieldName is dynamic; intSpecified, decimalTestSpecified, etc.

Example

if(decimalFieldSpecified == false){
  (source)decimalField? = null
}else{
 (source)decimalField? = decimalField
} 

What I have tried

   public static void GenericMappingWithNames(this Profile profile,
            Assembly assemblyFrom,
            Assembly assemblyTo,
            Func<Type, bool> typeFilter,
            string[] trimmedSuffixes = null)
        {
            var filteredFromTypes = assemblyFrom.GetTypes().Where(typeFilter).AsEnumerable();
            var typesTo = assemblyTo.GetTypes();

            foreach (var typeFrom in filteredFromTypes)
            {
                //Find types in assembly B with the same name. 
                var filteredTypesTo = typesTo.Where(x => TrimEnd(x.Name, trimmedSuffixes).Equals(TrimEnd(typeFrom.Name, trimmedSuffixes), StringComparison.InvariantCultureIgnoreCase));
                
                filteredTypesTo.ToList().ForEach(x =>
                {
                    //profile.CreateMap(typeFrom, x).ReverseMap();  

                    profile.CreateMap(typeFrom, x).ReverseMap().ForAllMembers(o =>
                    { 
                        var allSpecifiedMembers = o.GetType().GetProperties().Where(p=>p.Name.EndsWith("Specified")).ToList();

                        allSpecifiedMembers.ForEach((specified) =>
                        {
                            var propertyName = specified.Name.Replace("Specified", "");
                             
                            //hmm how do I get the (fieldName)specified value and check

                        }); 
                    }); 
                });
            }
        }

Type Examples

  public class Test
        { 
            public decimal test1 { get; set; }  
            public decimal test2 { get; set; }  
        }

        public class TestAgainst
        {
            public decimal test1 { get; set; }
            public bool test1Specified { get; set; }

            public decimal test2 { get; set; }
            public bool test2Specified { get; set; }

        }





Jpa AttributeConverter wrong value in field

I am trying to implement a JPA AttributeConverter for a column that converts a pojo to byte[]. It first encrypts the field in the pojo using a custom encryption util (that uses reflection) and then serialize it a to byte[] using Jackson objectMapper.

The source code for a demo app can be found here: https://bitbucket.org/bhaskar_/encryption-attribute-converter-demo/src/master/

This demo app has 3 test cases :

  1. To test the custom encryption util
  2. To test Jpa AttributeConverter using findById which passes
  3. To test Jpa AttributeConverter using findByRefId which fails

Any help in pin pointing the issue would be very helpful





dimanche 17 octobre 2021

C# Reflection help needed

 public partial class BaseClass : Form
{
    private bool myBaseBool;
    private NewClass newClass = new NewClass();

    public BaseClass()
    {
        InitializeComponent();
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        ChildClass childC = new ChildClass();
        newClass.NewClassInt = 50;
        childC.RunTest();
        bool testBool = myBaseBool;
    }

    private void DoSomething(int number, string text)
    {
        int i = number;
        string s = text;
    }
}

public class NewClass
{
    public int NewClassInt = 10;
}

public class ChildClass : BaseClass
{
    public void RunTest()
    {
        //Test one setting base class private testBool ------ Working
        var myObj = this;
        var myField1 = typeof(ChildClass).BaseType.GetField("myBaseBool", BindingFlags.Instance | BindingFlags.NonPublic);
        myField1.SetValue(myObj, true);
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        // Test two invoking base class private method -------- Working
        object[] ob = {1, "test"};
        typeof(ChildClass).BaseType.GetMethod("DoSomething", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(myObj, ob);
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        //Test three get value from base class instance of NewClass -------- Not Working
        var myField2 = typeof(ChildClass).BaseType.GetField("newClass", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
        var value = ((NewClass) myField2.GetValue(myObj)).NewClassInt;//Always gets the default value of NewClass
    }
}

}

Why is test three returning the default NewClassInt value and not returning the base class instance NewClassInt value?

Please no "why do you want to do that questions" I seen enough of them when it comes to the subject Reflection. All I'm doing is trying to learn.





How to get method name from PHP 8 attribute (reflection)

I'm working on small PHP framework (for learning). It has a file with LoginController class containing a method with Route attribute (code below). Is there any way to get the name of the method in the Route attribute class using Reflection?

Class with method using attribute:

class LoginController {
    #[Route('GET', '/login')]
    public function index() {
        // some code
    }
}

"Route" attribute class:

use Attribute;
use ReflectionMethod;

#[Attribute]
class Route {
    public function __construct($method, $routeUri) {
        // Can I get the method name ("index") from attribute instead of writing it?
        // And the class name?
        $reflection = new ReflectionMethod(\App\Controllers\LoginController::class, 'index');
        $closure = $reflection->getClosure();

        // Register a route...
        Router::add($method, $routeUri, $closure);
    }
}




How to dynamically create a form inside container using reflection?

I'm trying to create a generic library that is able to create one instance of a given Form. I'm using the WeifenLuo library.

In the main form, there is a dock container. If I create an instance directly in the method, it worked. However, when I call my generic method it shows the new Form outside the container.

private void button1_Click(object sender, EventArgs e)
        {
            // This works and put the new form inside the container
            Form1 form = new Form1();
            form.Show(mainFormDockPanel);
            // This just create the new form and open it outside the container
            //Forms.OpenForm<Form1, DockPanel>(this.mainFormDockPanel);
            Debug.WriteLine("Content: " + mainFormDockPanel.Contents.Count);
        }

Here is the generic function:

public static void OpenForm<T>(DockPanel dockPanel, T form = null, object obj = null, bool maximized = false) where T : class, new()
        {
            CreateMainForm();

            // Search for open forms
            foreach (DockContent frm in dockPanel).Contents)
            {
                // Verify if the content exists
                if (frm.GetType() == typeof(T) && obj == null)
                {
                    frm.Activate();
                    return;
                }
                // Check if the pressed button has a form
                if (obj != null && frm.GetType() == obj.GetType())
                {
                    frm.Activate();
                    return;
                }
            }

            if (form == null)
            {
                form = new T();
            }

            if (maximized)
                (form as DockContent).WindowState = FormWindowState.Maximized;

            Type type = typeof(T);
            MethodInfo methodInfo = type.GetMethod("Show", new Type[] { typeof(IWin32Window) });
            methodInfo.Invoke(form, new object[] { dockPanel });

            
        }

Do you guys realize what I'm missing?

Thanks in advance!





Cannot create dynamic type in .NET Core

I want to add Child as a dynamic type to a dynamic assembly:

public abstract class Parent { }       // I want to define this statically

public class Child : Parent {          // I want to define this dynamically
  private Child() : base() { }
}

I followed this example.

I added the nuget package System.Reflection.Emit (v 4.7.0).

Then wrote this:

using System;
using System.Reflection;
using System.Reflection.Emit;

public abstract class Base { }

public class Program {

  public static void Main() {

    // define dynamic assembly
    var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
    var moduleBuilder = assemblyBuilder.DefineDynamicModule(Guid.NewGuid().ToString());

    // define dynamic type
    var typeName = "Child";
    var typeBuilder = moduleBuilder.DefineType(
      typeName,
      TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout,
      typeof(Base));
    typeBuilder.DefineDefaultConstructor(MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
    //typeBuilder.CreateType();   // this was missing - see accepted answer below

    // test it
    try {
      typeBuilder.Assembly.GetTypes();                 // <--- throws
    }
    catch (ReflectionTypeLoadException exception) {
      Console.WriteLine(exception.Message);
    }
  }

}

It throws this:

Unable to load one or more of the requested types. Could not load type 'Child' from assembly '28266a72-fc60-44ac-8e3c-3ba7461c6be4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

This failed for me in a unit testing project. It also failed on dotnetfiddle.

What have I done wrong?