mardi 30 juin 2020

C#: How to set an Object's member by passing it a variable name and value

I have a class with a lot of properties (all Strings). I dynamically receive the name (and value) of a property to be set. Don't want to do a 100 if-then's to set the right variable. Would like to call something like:

Person.setVar(string propname,  string propvalue)

I have tried the following (based on my limited understanding through various posts here on SO):

using System;
using System.Reflection;

namespace MiscTest {
    public class Person {
        public string personName;
        public string personAge;

        public void SetVar(string propName, string propValue) {
            PropertyInfo propInfo = this.GetType().GetProperty(propName);
            propInfo.SetValue(this, propValue, null); //<--error here
        }
    }
}

However, keep running into this error ... something about Object reference not set:

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at MiscTest.Person.SetVar(String propName, String propValue) in C:\<long-path>\PropertyTest.cs:line 13

Any idea of what I might be doing wrong?





Create `SensorEvent` object using reflecion in Emulator not working

I want to create a SensorEvent object to simulate Sensor data. So i have used this reflection code to create SensorEvent

private fun getSensorEventObject(size : Int) : SensorEvent?{
    val cons = SensorEvent::class.constructors.toList()
    if (cons.isNotEmpty()) {
        return cons[0].call(size)
    }
    return null
}

This is working fine in real device. But when i run this code in Emulator this doesn't work. I got this exception

kotlin.reflect.full.IllegalCallableAccessException: java.lang.IllegalAccessException: Class java.lang.Class<kotlin.reflect.jvm.internal.calls.CallerImpl$Constructor> cannot access  method void android.hardware.SensorEvent.<init>(int) of class java.lang.Class<android.hardware.SensorEvent>

Not sure, as Emulator don't have real hardware is this the reason i am getting exception.

Is there any way i can create SensorEvent object when app is running in Emulator ?





NoSuchMethodException when using reflection with Spring JPARespository Methods (eg: findByName)

I'm trying implement multiple filters with JPA Query Methods offered by Spring Data JPA.

Dynamic filter eg: findByNameContainingCreatedAtBefore

(eg: findByName) and I used Java Reflection to get a method from JPA Repository and invoke dynamically.

Method method = institutionRepository.getClass().getMethod("findByName", String.class);

But the above line throws NoSuchMethodException.

Are there any ways to fix above issue?





Why are braces inserted in the code to call the getType method of TypeToken? [duplicate]

Why are there braces {} in the following code

Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();

If I understand correctly the normal Java syntax would be ClassName().MethodName(). Why are a space and the braces inserted between the class constructor and the getType method?





Get all properties of an object using reflection - but only the properties where the object has a value for them (not default value or null)

So I'm wanting to return the properties of an object, either generic or hard coded typeof(User) for e.g

However i only want to return the properties where the object I'm getting the properties for, has a value set against it, not the default value nor null. The reason for this is so that i can use these properties only to build an expression to only check these properties against columns in our database for items.

I tried something like this, however it still brings back all the values,

public User AutomatedUser {get;set;} // some properties of this will populated elsewhere

var props = typeof(User).GetProperties()
            .Where(pi => pi.GetValue(AutomatedFromUser) != pi.PropertyType.GetDefault());

I then found this method on the forum for getting default values of types, as compiler won't allow != default(pi.PropertyType) as "Pi" is a variable. Method below...

public static object GetDefault(this Type type)
    {
        // If no Type was supplied, if the Type was a reference type, or if the Type was a System.Void, return null
        if (type == null || !type.IsValueType || type == typeof(void))
            return null;

        // If the supplied Type has generic parameters, its default value cannot be determined
        if (type.ContainsGenericParameters)
            throw new ArgumentException(
                "{" + MethodInfo.GetCurrentMethod() + "} Error:\n\nThe supplied value type <" + type +
                "> contains generic parameters, so the default value cannot be retrieved");

        // If the Type is a primitive type, or if it is another publicly-visible value type (i.e. struct), return a 
        //  default instance of the value type
        if (type.IsPrimitive || !type.IsNotPublic)
        {
            try
            {
                return Activator.CreateInstance(type);
            }
            catch (Exception e)
            {
                throw new ArgumentException(
                    "{" + MethodInfo.GetCurrentMethod() + "} Error:\n\nThe Activator.CreateInstance method could not " +
                    "create a default instance of the supplied value type <" + type +
                    "> (Inner Exception message: \"" + e.Message + "\")", e);
            }
        }

        // Fail with exception
        throw new ArgumentException("{" + MethodInfo.GetCurrentMethod() + "} Error:\n\nThe supplied value type <" + type +
                                    "> is not a publicly-visible type, so the default value cannot be retrieved");
    }
}

Any tips or help would be greatly appreciated as to why this wouldn't be working, or where i'm going wrong.





How to dynamically instantiate all fields of certain generic type?

I have a base type like this:

public class Group    {}

public class Group<T> : Group where T : class
{
    public Group()
    {
        InitAllGroupTypeInstances(this as T);
    }
}

And an instantiation method like this:

        public static void InitAllGroupTypeInstances<Thost>(Thost instance)
        {
            if (instance == null)
                return;

            var t = typeof(Group);
            while (true)
            {
                foreach (var Fi in typeof(Thost)
                    .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                    .Where(fi => t.IsAssignableFrom(fi.FieldType)).ToList()) {
                    var n = Fi.Name;
                    if (Fi.FieldType != typeof(Type)) {
                        var it = (Group) Fi.GetValue(instance);
                        if (it == null) {
                            var Tgroup = typeof(Group<>);
                            Type[] typeArgs = {Fi.FieldType};
                            var Ttarget = Tgroup.MakeGenericType(typeArgs);
                            Fi.SetValue(instance, (Group) Activator.CreateInstance(Ttarget));
                        }
                    }
                }

                t = t.BaseType;
                if (t == null ||
                    t == typeof(Group)) {
                    break;
                }
            };
        }

I want to create an instance of something like this:

public class SimpleTwoHostNetwork : Group<SimpleTwoHostNetwork>
{
    public SimpleNetwork FromA, FromB;

    public SimpleTwoHostNetwork() : base() {}
}

public class SimpleNetwork : Group<SimpleNetwork> {
    public SimpleNetwork() {}
}

So that all the fields that are SimpleNetwork would construct themselves automagically. Yet I get an error like this:

enter image description here

System.ArgumentException: "Object of type 'ServicesPetriNet.Core.Group`1[ServicesPetriNet.Examples.SimpleTwoHostNetwork+SimpleNetwork]' cannot be converted to type 'ServicesPetriNet.Examples.SimpleTwoHostNetwork+SimpleNetwork'."

So I wonder what do I do wrong and how to dynamically instantiate all fields of certain generic type?





lundi 29 juin 2020

GetReferencedAssemblies throws "Operation is not supported on this platform"

I am working on .net standard library and I am trying to get all referenced assemblies from entry assembly.

Here is my code

AssemblyName[] allAssemblies = Assembly.GetEntryAssembly().GetReferencedAssemblies();

This code is working perfectly in debug mode , and i am able to get all referenced assemblies from the entry assembly(UWP app) .

But in release mode GetReferencedAssemblies() throws System.PlatformNotSupportedException: 'Operation is not supported on this platform.' exception , and am not able to get the referenced assemblies in uwp app.

Can anyone help me to solve this.

Thanks in advance.





Why should we use reflection instead of direct object creation?

I'm a newbie in java and I was studying about polymorphism pattern and I encountered reflection in polymorphism. I actually don't know much about it and wanted to ask you about the benefits of it. for example I wrote this code that has an interface class name "Ieat" and some other classes that implements the eat(); method of the Ieat.

public interface Ieat {

    public void eat();
}

///////////////////////

public class Person implements Ieat{

    String name;
    int age;

    @override
    public void eat(){
    system.out.println("eat");
    }

}

////////////////////////

public class Student extends Person{

    String name;
    int age;

    @override
    public void eat(){
    system.out.println("student eat");
    }

}

//////////////////////////////

public class Worker extends Person{

    String name;
    int age;

    @override
    public void eat(){
    system.out.println("worker eat");
    }

}

///////////////////////////////

public static void main (Strings[] args){
    
    Person s = new Student;
    s.eat();

    Person w = new Worker();
    w.eat();

}

in this code I directly used "new" to create the object and override its function.

the most important question that I'm dealing with is how to use reflection and put those implementation classes in config.xml files so we can read from them? and how do we use "forName" function to do so?

I'd be thankful if you can explain it, I've been dealing with this for a loooooong time :(





samedi 27 juin 2020

LINQ Generic IQueryable

Let's say I have a DBContext with 3 DBSets:

public class DatabaseContext : DbContext
{
    public DbSet<A> As { get; set; }
    public DbSet<B> Bs { get; set; }
    public DbSet<C> Cs { get; set; }
}

class A
{
    public string Text { get; set; }
    public string Code { get; set; }
}

class B
{
    public string Name { get; set; }
    public string Code { get; set; }
}

class C
{
    public string Book { get; set; }
    public string Code { get; set; }
}

I want to write a generic method that:

  1. Generically takes any of the three DbSet as the first argument
  2. Takes a string value as the second argument
  3. Without casting to IEnumerable, returns the first record in the provided DbSet where the Code field matches the provided string

So far I have this method:

public static T GetCode<T>(IQueryable<T> set, string code) where T : class
{
    var Prop = typeof(T).GetProperty("Code");
    return set.Where(x => (string)Prop.GetValue(x) == code).FirstOrDefault();
}

When I try to call it using this line:

var _A = GetCode(TheDB.As, "123");
var _B = GetCode(TheDB.Bs, "123");
var _C = GetCode(TheDB.Cs, "123");

I get this error:

InvalidOperationException:

The LINQ expression 'DbSet<A>.Where(m => (string)__Prop_0.GetValue(m) == __code_1)' could not be translated.

Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().

How can I write the WHERE clause on the DbSet that is able to translate properly for IQueryable? My method works if I cast the IQueryable to an IEnumerable, but I don't want to do that, since the set may potentially be very large and I want the database (not my application) to do the record searching.





Java class that represent method name and formal parameters

Is there a JDK Java class that represents a method name and formal parameters without the declaraing class. If I use the Java class Method from java.lang.reflect I usually get

too much information:

public class Method

clazz: The declaring class
name: The method name
parameterTypes: The formal parameters
Etc..

I am seeking a class which already exists in the JDK and which would cover:

public class ??

name: The method name
parameterTypes: The formal parameters

Best Regards





Get Enum Member by Value Attribute [duplicate]

How can I retrieve enum member using Value attribute.

public enum State
{
    [JsonIgnore] Undefined = 0,
    [EnumMember(Value = "Connecticut")] CT = 7,
    [EnumMember(Value = "Massachusetts")] MA = 33,
    [EnumMember(Value = "Maine")] ME = 19,
    [EnumMember(Value = "New Hampshire")] NH = 23
}

How would I retrieve CT using or by "Connecticut"? I am finding a lot of opposite examples (i.e. get value by member).





vendredi 26 juin 2020

NoSuchMethodException while accessing Kotlin Data class using reflection

I keep getting the following error while tryign to use reflection to access a kotlin data class java.lang.NoSuchMethodException: <init> [interface java.util.List, class java.lang.Boolean]

List<String> names = new ArrayList();
boolean isValid = false;
Class[] type = { List.class, Boolean.class };
Class dataClass = Class.forName("com.randome.model.Data");
Constructor DataConstructor = dataClass.getConstructor(type); // problem here 
Object[] dataObject = { names, isValid };
Object data = inAppContactDataConstructor.newInstance(dataObject);

// Data Class

@Parcelize
data class Data(
    val names: List<String>,
    val isValid: Boolean
): Parcelable




Why is Parser of MessageDescriptor null when obtaining it via FileDescriptor.BuildFromByteStrings()?

I have compiled the example addressbook.proto file into a binary file addressbook.proto.bin with the --descriptor_set_out option of protoc. I want to load this file at runtime and use it with the reflection API. At the moment I evaluate what's possible and what's not.

I found this comment on github suggesting that some amount of reflection is possible with FileDescriptor.BuildFromByteStrings() and have written some code based on that:

static void Main(string[] args)
{
    var john = new Person
    {
        Id = 1234,
        Name = "John Doe",
        Email = "jdoe@example.com",
        Phones = { new PhoneNumber { Number = "555-4321", Type = PhoneType.Home } }
    };

    using (var output = File.Create("john"))
    {
        john.WriteTo(output);
    }

    using (var stream = File.OpenRead("addressbook.proto.bin"))
    {
        var descriptorSet = FileDescriptorSet.Parser.ParseFrom(stream);
        var byteStrings = descriptorSet.File.Select(f => f.ToByteString()).ToList();
        var messageDescriptors = FileDescriptor
            .BuildFromByteStrings(byteStrings) // Note: reflection using the returned FileDescriptors is not currently supported.
            .SelectMany(descriptor => descriptor.MessageTypes)
            .ToArray();

        #region this works

        foreach (var messageDescriptor in messageDescriptors)
        {
            Console.WriteLine(messageDescriptor.Name);
        }

        #endregion

        #region this fails

        var personMessageDescriptor = messageDescriptors.First(message => message.Name == "Person");
        using (var input = File.OpenRead("john"))
        {
            Console.WriteLine(
                new JsonFormatter(JsonFormatter.Settings.Default)
                    .Format(personMessageDescriptor.Parser // Parser is null =(
                        .ParseFrom(input)));
        }

        #endregion
    }
}

There's a note in the comment of that method stating:

Note: reflection using the returned FileDescriptors is not currently supported.

However, it is actually possible to list the Names of all MessageTypes jsut fine (see first #region) On the other hand, the Parser property is null.

Is Parser being null the limitation for reflection mentioned in the quoted note above or is it a mistake in my programming?





Reflections in a API sharing same package

So i'm messing around with Reflections in my API for a plugin system and its all working but once i have 2 jars using the same API it seems to use the same packages as shown below

[DiamondBank] and [UpdateNotifier] are two separate jars

[14:36:38] [Server thread/INFO]: com.cube.notifier
[14:36:38] [Server thread/INFO]: [UpdateNotifier] Registered 3 Commands.
[14:36:38] [Server thread/INFO]: package com.cube.notifier.commands
[14:36:38] [Server thread/INFO]: package com.cube.notifier.commands
[14:36:38] [Server thread/INFO]: package com.cube.notifier.commands
[14:36:39] [Server thread/INFO]: [DiamondBank] Enabling DiamondBank v1.1
[14:36:39] [Server thread/INFO]: [DiamondBank] Starting DiamondBank
[14:36:39] [Server thread/INFO]: [DiamondBank] Registered 2 Events.
[14:36:39] [Server thread/INFO]: org.cube.diamondbank
[14:36:42] [Server thread/INFO]: [DiamondBank] Registered 3 Commands.
[14:36:42] [Server thread/INFO]: package com.cube.notifier.commands
[14:36:42] [Server thread/INFO]: package com.cube.notifier.commands
[14:36:42] [Server thread/INFO]: package com.cube.notifier.commands

Now i tried to hardcode the path per plugin using a string but i get the same result but it prints out the correct location as seen above

This is my method that loads the commands

 val config = ConfigurationBuilder()
        .addScanners(
            SubTypesScanner(false),
            TypeAnnotationsScanner(),
            MethodAnnotationsScanner()
        )
        .addUrls(MinecraftCommand::class.java.getResource(""))


    println(packageName)
    val reflection = Reflections(ClasspathHelper.forPackage(packageName),MethodAnnotationsScanner())
    val cds = reflection.getMethodsAnnotatedWith(MinecraftCommand::class.java)
    if(cds.size != 0) {
        plugin.logger.info { "Registered ${cds.size} Commands." }
        cds.forEach {
            println(it.declaringClass.`package`.toString())
        }
    }

Any help would be Amazing thank you so much.





How to pass different annotations with the same property as a method parameter and have the ability to use that property?

CASE

I have a class whose responsibility is to compare field by field two instances of a DTO class for a certain subset of all DTO instance fields and collect "pretty" names of the fields whose values are different. Other fields may be added in the future and they may or may not be included in this comparison.

To allow for this expansion, this is currently implemented as follows: a field that needs to be included in the comparison logic is annotated with a custom annotation and its pretty name is passed as the annotation parameter.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ComparableField {
  String prettyName();
}

public class Dto {
  private String field1; //not included in the comparison logic

  @ComparableField(prettyName="Pretty field 2")
  private String field2;

  @ComparableField(prettyName="Pretty field 3")
  private String field3;
}

The aforementioned class uses reflection to iterate through all the fields of the DTO class and check if that annotation is present, compares the values, and, if different, adds the pretty name to a set.

public Set<String> getAnnotatedDifferentFields(Dto dto1, Dto dto2) {
  Set<String> result = new HashSet<>();
  Field[] declaredFields = dto1.getClass().getDeclaredFields();
  Arrays.stream(declaredFields)
      .filter(field -> field.isAnnotationPresent(ComparableField.class))
      .forEach(field -> {
          field.setAccessible(true);
          if (!field.get(dto1).equals(field.get(dto2)) {
            result.add(field.getAnnotation(ComparableField.class).prettyName());
          }
      });

  return result;
}

I missed exception handling and other complications on purpose.

PROBLEM

There's a new requirement now: all "comparable" fields will have some logical groupings and the resulting sets should be different as well.

QUESTION

Is there an elegant way to implement this requirement along the same lines? I was thinking having different annotations for different logical groups and calling the method with the required annotation as a method parameter:

public Set<String> getAnnotatedDifferentFields(Dto dto1, Dto dto2, Class<? extends Annotation> annotationClass) {
  Set<String> result = new HashSet<>();
  Field[] declaredFields = dto1.getClass().getDeclaredFields();
  Arrays.stream(declaredFields)
      .filter(field -> field.isAnnotationPresent(annotationClass))
      .forEach(field -> {
          field.setAccessible(true);
          if (!field.get(dto1).equals(field.get(dto2)) {
            result.add(field.getAnnotation(annotationClass).prettyName()); //compile error here
          }
      });

  return result;
}

But this of course gives me a compile error because annotationClass is now generic and might not have the prettyName property. There's also no such thing as annotation inheritance, wherebe I would create a parent annotation with the property and several child annotations. I also thought about annotating my custom annotations with another annotation but that wouldn't work either.





jeudi 25 juin 2020

Access inner class Parent KType reflectivly in kotlin

I'm trying to instantiate an inner class reflectively using Kotlin-reflection library it's not hard except that I need to pass an instance of the parent class to the child class constructor.

Is there any function/way to get the KType of the parent class (without using it's name and Class.forName())?

here is an example of what I'm trying to achieve:

class Parent {
    inner class Child()
}
fun main() {
    val childType: KType = typeOf<Parent.Child>()
    val parentType = childType.getParent()
}




Build Expression tree to Add elements to Collection dynamically c#

I have a class and I need to iterate tru each property reading the attribute name to map to my data Source the value, in the cases where I have a ICollection that property will have multiple attributes to map the correct value.

I'm using Expression trees to set the values efficiently to each property but I'm having issues to set the values to the Collection. I think this is because I need to create an instance of that Collection but I don't know. I'm a bit lost on that one here's what I got:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class MapToAttribute : Attribute
{
    public MapToAttribute(string field)
    {
        Field = field;
    }

    public string Field { get; private set; }
}

public class MyDataClass
{
    [MapTo("one")]
    public int propOne { get; set; }

    [MapTo("two")]
    public string propTwo { get; set; }

    [MapTo("item1")]
    [MapTo("item2")]
    [MapTo("item3")]
    public ICollection<int> collection { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var setter = SetValues<MyDataClass>();
    }

    private static IEnumerable<T> SetValues<T>()
        where T : new()
    {
        var properties = GetClassProperties<T>();
        var results = new List<T>();

        for (int x = 1; x<=100; x++)
        {
            var row = new T();

            //Simulated Datasource
            var dataSource = new Dictionary<string, object>();
            dataSource.Add("one", x);
            dataSource.Add("two", x.ToString());
            dataSource.Add("item1", x);
            dataSource.Add("item2", x+x);
            dataSource.Add("item3", x*x); 

            foreach (var property in properties)
            {
                //this line executes the Action
                property.Value(row, dataSource[property.Key]);
            }
            results.Add(row);
        }
        return results;
    }

    private static Dictionary<string, Action<T, object>> GetClassProperties<T>()
    {
        var setters = new Dictionary<string, Action<T, object>>();

        var instance = Expression.Parameter(typeof(T));
        var argument = Expression.Parameter(typeof(object));

        foreach (var property in typeof(T).GetProperties())
        {
            var names = property.GetCustomAttributes(typeof(MapToAttribute), true)
                .Select(p => ((MapToAttribute)p).Field);

            var setter = Expression.Lambda<Action<T, object>>(
                  Expression.Call(
                        instance,
                        property.GetSetMethod(),
                        Expression.Convert(argument, property.PropertyType)
                  ), instance, argument
                ).Compile();

          // Due to the types I cannot just assign a value to a ICollection,
          // that's why I tried to create HERE a different setter 
          // when the property Type is ICollection, I commented out the code failing.
          
            //var getCollection = Expression.Lambda<Func<T, object>>(
            //        Expression.Call(
            //            instance,
            //            prop.GetGetMethod()
            //        ), instance
            //      ).Compile();

            //Action<T, object> setter = (classInstance, value) =>  
            // getCollection(classInstance).Add(value);


            foreach (var name in names)
            {
                setters.Add(name, setter);
            } 
        }

        return setters;
    }
}




nable to load one or more of the requested types.\r\nCould not load file or assembly 'System.Data.SqlClient, Version=4.6.1.0

I have an application written on the top of ASP.NET Core 3.1.

When I use reflection to get the types in my project, I get the following exception

Unable to load one or more of the requested types.
Could not load file or assembly 'System.Data.SqlClient, Version=4.6.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

I am not sure what package depends on System.Data.SqlClient but my app does not depend on System.Data.SqlClient package.

I tried to install the System.Data.SqlClient into my project the following command, but I am still getting the same error.

Install-Package System.Data.SqlClient -Version 4.6.1

Here is my code

// Loading the dlls.
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();

var referencedPaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
var loadables = referencedPaths.Where(r => !loadedAssemblies.Select(a => a.Location).Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList();

foreach(var loadable in loadables)
{
    try
    {
        loadedAssemblies.Add(AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(path)));
    }
    catch { }
}


Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
List<Type> types = new List<Type>();

foreach (var assembly in assemblies)
{
    try
    {
        types.AddRange(assembly.GetTypes());
    }
    catch (Exception e)
    {
        // I get the exception here 
        // Unable to load one or more of the requested types.
        // Could not load file or assembly 'System.Data.SqlClient, Version=4.6.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
    }
}

How can I determine what is causing this issue? How can I solve it?





Unity: Access Editor specific type from inside running Editor

Basically I want to run a static function from inside game code that targets an editor script inside the Editor folder where the function and type are static. I'm unsure what assembly the editor scripts will be in, if this is the correct way to call them, and if it's even possible to access the assembly that custom editor scripts are inside from running code (inside the editor though, no requirement to run on builds)

essentially trying to do

System.Reflection.Assembly editorAssembly = null;
        System.Reflection.Assembly[] allAssemblies = System.AppDomain.CurrentDomain.GetAssemblies();
        foreach (System.Reflection.Assembly assem in allAssemblies)
        {
            if (assem.FullName == "???UnityEditorMaybe?")
            editorAssembly = assem;
        }
        Type MyStaticType = editorAssembly.GetType("MyStaticType");
        MyStaticType .GetMethod("DoThing").Invoke(null,null);




Explanation of use for Java Reflection [closed]

I hope this is an okay question for this board. If it is not, please let me know immediately and I will pull it. Also, if it belongs on another board, I would appreciate knowing which board that would be.

I am reviewing Java Reflection for a class. We students were just given a link to the Oracle tutorial and told to read it. I've read it, but I'm having trouble understanding how it would be used in real life.

Can anyone share with me a real-life example of where Reflection would be necessary? I'm not looking for code. Rather, I'm looking for something like this: "Suppose you have a program that does ____. Here is the situation where that program would require Reflection to do ____." Or something like that. I'm just trying to conceptualize where I might see a situation come up where I would find a need for it. I just think it might help me understand it better.

Thanks for any input you can share.





Casting argument before using reflection to invoke a method

I try to using reflection to set a value from A model to B model

   // Get value in Board model using dynamic getter
   Object lvBoardValue;
   // Value after invoke getter is (Double)
   lvBoardValue = lvBoardPropDesc.getReadMethod().invoke(pBoardModel);
   // Return type of getter in Instrument  => (int)
   Class lvInstReturnType = lvInstrumentPropDesc.getReadMethod().getReturnType();
   // Return type of getter in Board => (double)
   Class lvBoardReturnType = lvBoardPropDesc.getReadMethod().getReturnType();
                
   // set that value for instrument (This setter need int value)
   lvInstrumentPropDesc.getWriteMethod().invoke(pBaseModel, (int) lvBoardValue);

The problem is I want to set a Double value (lvBoardValue) by invoking another setter which is need int value. I googled a lot the way to cast from Double to int, but have no clue.

I have tried:

lvInstrumentPropDesc.getWriteMethod().invoke(pBaseModel, ((Double) lvBoardValue).intValue());

It should work by casting like that, but it cannot meet the requirement of setting dynamically if I could have a return type

Have anyone already face this situation?. Please give me a suggestion. Thank you in advance.





mercredi 24 juin 2020

Reconstruct MethodInfo of function returned by another function for later execution

Considering the following code:

void Main()
{
    var f1 = (IO<int, int>)Functions.AddOne;
    f1.GetType().DeclaringType.AssemblyQualifiedName.Dump("AddOne type");
    f1.GetMethodInfo().DeclaringType.AssemblyQualifiedName.Dump("AddOne MethodInfo type");
    f1.GetMethodInfo().Name.Dump("AddOne MethodInfo name");
    
    Type.GetType(f1.GetType().DeclaringType.AssemblyQualifiedName).AssemblyQualifiedName.Dump("AddOne reconstructed type");
    var type1b = Type.GetType(f1.GetMethodInfo().DeclaringType.AssemblyQualifiedName);
    type1b.AssemblyQualifiedName.Dump("AddOne reconstructed MethodInfo declaring type");
    type1b.GetMember(f1.GetMethodInfo().Name).First().Name.Dump("AddOne reconstructed MethodInfo name");
    
    var f2 = Curry<int, int>(Functions.AddOne, 6);
    f2.GetType().DeclaringType.AssemblyQualifiedName.Dump("Curried type");
    f2.GetMethodInfo().DeclaringType.AssemblyQualifiedName.Dump("Curried MethodInfo type");
    f2.GetMethodInfo().Name.Dump("Curried MethodInfo name");
    
    Type.GetType(f2.GetType().DeclaringType.AssemblyQualifiedName).AssemblyQualifiedName.Dump("Curried reconstructed type");
    var type2b = Type.GetType(f2.GetMethodInfo().DeclaringType.AssemblyQualifiedName);
    type2b.AssemblyQualifiedName.Dump("Curried reconstructed MethodInfo declaring type");
    type2b.GetMember(f1.GetMethodInfo().Name).Dump("Curried reconstructed MethodInfo");
}

public static class Functions {
    public static void AddOne(int a, out int b) {
        b = a + 1;
    }
}

public delegate void O<TO1>(out TO1 out1);
public delegate void IO<TI1, TO1>(TI1 in1, out TO1 out1);

public static O<TO1> Curry<TI1, TO1>(IO<TI1, TO1> f, TI1 in1) => (out TO1 out1) => f(in1, out out1);

f1 is correctly reconstructed:

AddOne type:

UserQuery, LINQPadQuery, Version=1.0.0.713, Culture=neutral, PublicKeyToken=null

AddOne MethodInfo type:

UserQuery+Functions, LINQPadQuery, Version=1.0.0.713, Culture=neutral, PublicKeyToken=null

AddOne MethodInfo name:

AddOne

AddOne reconstructed type:

UserQuery, LINQPadQuery, Version=1.0.0.713, Culture=neutral, PublicKeyToken=null

AddOne reconstructed MethodInfo declaring type:

UserQuery+Functions, LINQPadQuery, Version=1.0.0.713, Culture=neutral, PublicKeyToken=null

AddOne reconstructed MethodInfo name:

AddOne

So I can re-execute it at a later execution of my program.

However, f2 is not:

Curried type:

UserQuery, LINQPadQuery, Version=1.0.0.713, Culture=neutral, PublicKeyToken=null

Curried MethodInfo type:

UserQuery+<>c__DisplayClass8_0`2[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], LINQPadQuery, Version=1.0.0.713, Culture=neutral, PublicKeyToken=null

Curried MethodInfo name:

b__0

Curried reconstructed type:

UserQuery, LINQPadQuery, Version=1.0.0.713, Culture=neutral, PublicKeyToken=null

Curried reconstructed MethodInfo declaring type:

UserQuery+<>c__DisplayClass8_0`2[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], LINQPadQuery, Version=1.0.0.713, Culture=neutral, PublicKeyToken=null

Curried reconstructed MethodInfo:

(0 items)

Is there a way to reconstruct such a function returned from another function such that it can be re-executed at a later execution of my program?





Golang concrete type from interface {} without knowing the type

If I have a variable that is interface{}, how do I actually get the values in a concrete type without any prior knowledge of the original structure of the interface{}?

For example lets say I have an interface{} that is really a []struct{abc string} and I don't know that its actually []struct{abc string}, how do I convert interface{} to []struct{abc string}? I don't mind using reflection.





Ambiguous Entry System.Reflection

Im getting a error when im parsing a method trough system.reflection:

System.Reflection.AmbiguousMatchException

typeof(Graphics).GetMethod("DrawRectangle").Invoke(g, new object[] {
     Pens.Red, new Rectangle(200, 200, 100, 50)
});

however it works nice when im parsing it trough the compiler

g.DrawRectangle(Pens.Red, new Rectangle(200,200,100,50));

is there a way to specify which method i want to call?





how to get methods code from a file in php without removing back to line and tabs

i m trying to make a function that can read a file and return the name of methods and their correspond code " similar to reflection but reflections remove return to line and tabs and i wanna keep them to show them out in the editor . i tried this but it removes the spaces and back to line

function get_sourcecode($classname, $methodename) {

$func = new ReflectionMethod($classname, $methodename);
$filename = $func->getFileName();
$start_line = $func->getStartLine() - 1; // it's actually - 1, otherwise you wont get the function() block
$end_line = $func->getEndLine();
$length = $end_line - $start_line;

$source = file($filename);
$body = implode("", array_slice($source, $start_line, $length));

return $body;

}





Scala reflection to get List field value by universe apply

I defined an annotation class with a List field in Scala:

class TestAnnotation(a: String, b: List[String]) extends StaticAnnotation

And some classes using the annotation, e.g.:

@TestAnnotation("test", List("b1", "b2"))
class TestA

Now I want to get the class annotation values, a and b, by reflection

import scala.reflect.runtime.universe

universe
  .typeOf[TestA]
  .typeSymbol
  .annotations
  .find(_.tree.tpe =:= universe.typeOf[TestAnnotation])
  .map(_.tree).foreach(t => {
    // Match Exceptions happen there! How to match the List fields?
    val universe.Apply(_, universe.Literal(universe.Constant(a: String)) :: universe.Literal(universe.Constant(b: List[String])) :: Nil) = t 
    println(a)
    println(b)
  })

How to get the List value from deconstructing t by matching it against universe.Apply?





Kotlin check if data class properties are all null

Suppose I have a data class with nullable properties:

data class User(
   val fName: String?,
   val lName: String?)

In a function where I receive an instance of such a class even if the instance is not null I want to check that at least one of the properties inside is initialized and not null. I know that I can check the properties one by one, but I want to have something more generic, I googled and seems Kotlin there is no extension function for this so I implemented one and would like to share with you and check if anyone knows better ways.





mardi 23 juin 2020

Java Reflection with Annotation Class not working

I'm pretty experienced with Java, however a novice to using Reflection and Annotation classes, which I'm trying to learn for fun. To get some practice, I made an Identifiable class which is designed to add several helpful methods to any class it inherits.

Here is the full class:

abstract class Identifiable<T, K extends Comparable<K>> implements Comparable<Identifiable<T, K>> {

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Identifier { }

    private static Method getMethodAnnotatedWith(final Class<?> type) {
        return Arrays.stream(type.getDeclaredMethods())
                .filter(m -> m.isAnnotationPresent(Identifier.class))
                .findFirst()
                .orElse(null);
    }

    private K id;

    @SuppressWarnings("unchecked")
    public Identifiable(Class<T> clazz) {
        var m = getMethodAnnotatedWith(clazz);
        if (m == null) throw new IllegalArgumentException(
            clazz.toString() + " does not have a method annotated by @Identifier"
        );

        try {
            id = (K) m.invoke(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int compareTo(@NotNull Identifiable<T, K> i) {
        return id.compareTo(i.id);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Identifiable<?, ?> that = (Identifiable<?, ?>) o;
        return id == that.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

And here is how I am trying to design it to work:

class Foo extends Identifiable<Foo, Integer> {
    private final int i;

    Foo(int i) {
        super(Foo.class);
        this.i = i;
    }

    @Identifier
    int getI() {
        return i;
    }
}

However, id is always 0 for some reason, so I'm not sure if it's a problem with my Identifier annotation class or the way I'm using reflection. I'm pretty sure it's the latter since while debugging, I found that it is able to access the method with the annotation. Any help would be appreciated, thanks!





how to type to class name in c#

public class FoodA
{
    public static int Eat()
    {
        return 1 ;
    }
    public static int Eat(int a, int b)
    {
        return a+b ;
    }
}

public class FoodB
{
    public static int Eat()
    {
        return 22 ;
    }
    public static int Eat(int a, int b)
    {
        return a*b ;
    }
}

// Is it possible ??
{
    Type tFood = System.Type.GetType("FoodA");
    tFood.Eat()           //  return 1
    tFood.Eat(2, 3)           //  return 5

    tFood = System.Type.GetType("FoodB");
    tFood.Eat()           //  return 22
    tFood.Eat(2, 3)           //  return 6
}

Is there a way to use different class depending on the situation?

        Type type = Type.GetType("FoodA");
        MethodInfo meth = type.GetMethod("Eat") ;
        object ob = Activator.CreateInstance(type,null);
        meth.Invoke(ob, null) ;

The above method is a bit complicated and the function of the same name is not used. Please answer.





C# How to init property (without setter) by reflection

Task: Serialize a list of objects into a byte[] using protobuf.

Without reflection all is good

.proto

message MyObject{
  int32 id = 1;
  int32 value = 2;
}

message MyObjects {
  repeated MyObject objects = 1;
}

.cs

public static byte[] ToByteArray(List<MyObject> obj) {
    var objects = new MyObjects {
        Objects = {obj}
    };
    return objects.ToByteArray();
} 

Since I need to serialize many different types in this way, I want to write a universal method using reflection.

Problem: Protobuf itself generates entities and properties for them, but it does not create a setter for RepeatedField, which means that I can not set the value using GetProperty("Objects")?.SetValue(objects, obj). System.ArgumentException: Set Method not found for 'Objects'

.cs (protobuf generated)

public pbc::RepeatedField<global::Test.MyObject> Objects {
  get { return objects_; }
}

.cs

public static byte[] ToByteArray<T, E>(List<T> obj) where T : IMessage where E : IMessage {
    var objects = Activator.CreateInstance<E>();
    objects.GetType().GetProperty("Objects")?.SetValue(objects, obj);
    return objects.ToByteArray();
} 

Question: How to use reflection to set values ​​for a property during object creation, just as I do it without reflection?

How to write this "new MyObjects {Objects = {obj}}; (where obj: IEnumerable)" using reflection

Various conclusions:

  • I noticed that filling properties that do not have a setter is only possible for collections and only when creating an object.
  • Most likely I need an alternative way to instantiate the class. Activator.CreateInstance() is not fulfilling my task.




How to get a specific constructor that matches an Interface?

So playing with my own test Dependency Injector class. (yeah tons out there but this is just for fun)

Works decent but I don't know how to get the correct constructor based on the Interface passed in.

internal class DiContainer
{
    private readonly Dictionary<Type, RegistryRecord> registry = new Dictionary<Type, RegistryRecord>();

    private static DiContainer instance;

    private DiContainer()
    {
    }

    public static DiContainer GetInstance()
    {
        return instance ??= new DiContainer();
    }

    public void Register<T, C>() where C : class, T
    {
        registry.Add(typeof(T), new RegistryRecord
        {
            InterfaceType = typeof(T),
            ConcreteType = typeof(C),
            IsSingleTon = false
        });
    }

    public void Register<C>() where C : class
    {
        Register(typeof(C));
    }

    public void Register(Type t)
    {
        registry.Add(t, new RegistryRecord
        {
            InterfaceType = t,
            ConcreteType = t,
            IsSingleTon = false
        });
    }

    public void RegisterSingleton<T, C>(C instance = null) where C : class, T
    {
        registry.Add(typeof(T), new RegistryRecord
        {
            InterfaceType = typeof(T),
            ConcreteType = typeof(C),
            IsSingleTon = true,
            Instance = instance
        });
    }

    public T Get<T>()
    {
        return (T) Get(typeof(T));
    }

    
    public object Get(Type t)
    {
        ConstructorInfo constructor;

        RegistryRecord r = null;

        if (t.IsInterface && registry.ContainsKey(t))
        {
            r = registry[t];

            if (r.IsSingleTon && r.Instance != null) return r.Instance;

            constructor = r.ConcreteType.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0];
        }
        else
        {
            //todo how do we select the correct constructor?
            constructor = t.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0];
        }

        var parameters = constructor.GetParameters();

        //recurse to build dependency chain
        var objects = parameters.Select(parameter => Get(parameter.ParameterType)).ToList();

        var obj = constructor.Invoke(objects.ToArray());

        if (r != null && r.IsSingleTon)
        {
            r.Instance = obj;
        }

        return obj;
    }

}


internal class RegistryRecord
{
    public Type InterfaceType { get; set; }
    public Type ConcreteType { get; set; }
    public object Instance { get; set; }
    public bool IsSingleTon { get; set; }

}

So the problem is:

constructor = t.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0];

I am just assuming the first constructor which is awful. But I have the definition of the interface I could be using.

How do I get the parameters of my interface and check them against the constructor?

Would like to select a constructor that matches the interface, or at least partially matches optimally.





Umbraco 8: Get reference to DocumentType definition in WebAPI class

Q) How do I get a reference to a DocumentType definition in my UmbracoAPIController class, so that I can do LINQ queries on the properties?

Background:
I've got a WebAPI endpoint I call from JS, that fetches Book items from my DB. I want to filter based on an input variable, such as ISBN, in my LINQ query. In order to do that, I need to get the DocumentType definition imported in my UmbracoAPIController class.

Trying the below, where Book is the type I want to cast to:

var parent = Umbraco.ContentAtRoot().First().Children().FirstOrDefault(x => x.Name == "Booklist");
if (parent != null) 
{
    var isbn = HttpContext.Current.Request.Params["isbn"];

    var books = parent.Children().Cast<Book>().Where(b => b.Isbn == isbn);

    foreach (var book in books) 
    {
        // Do something here....
    }
}

Breaks with the error:

 The type or namespace name 'Book' could not be found (are you missing a using directive or an assembly reference?)

Note: Please don't tell me I'm just doing everything the 'wrong' way unless you have a clear, better alternative, thank you.





Setting and Getting of Values using Scala Reflection

I have a patient resource of below type:

val p:Patient = new Patient  

which comes under below package:

import org.hl7.fhir.r4.model.Patient

Now, I want to set some value for it like one ID attribute with value like example and when I try something like p.getId() I should be able to retrieve it. I was trying scala reflection and desgined below methods by referring one of the posts but not sure how to use it over here. Below are the methods for get and set:

object ReflectionDryRun {
  def main(args: Array[String]): Unit = {    
    val p:Patient=new Patient
    reflector(p.setV(idValue))
    
  }
  implicit def reflector(ref: AnyRef) = new {
    def getV(name: String): Any = ref.getClass.getMethods.find(_.getName == name).get.invoke(ref)
    def setV(name: String, value: Any): Unit = ref.getClass.getMethods.find(_.getName == name + "_$eq").get.invoke(ref, value.asInstanceOf[AnyRef])
  }   

Unable to set value of idValue using reflector method. Please guide me through it





lundi 22 juin 2020

Kotlin: How can I determine the extension function exists

Suppose I have a function (in Kotlin over Java):

fun <E> myFun() = ...

where E is a general type I know nothing about. Can I determine within this function whether there exists an extension function E.extFun()? And if so, how?





Kotlin: Assert Immutability

I have class that internally maintains a mutable list, and I want to provide an immutable view on this list. Currently I'm using the following:

/**The list that actually stores which element is at which position*/
private val list: MutableList<T> = ArrayList()

/**Immutable view of [list] to the outside.*/
val listView: List<T> get() = list.toList()

First question: Can this be done easier

Second question: How can I test that listView is actually immutable. I guess reflections are necessary?





Collection Contents of Private Java Fields

Let's assume I have a class that looks something like:

public class HasCollection() {
  private List<Class> exceptions;
}

In this example, exceptions is a private collection of any kind of exception (Runtime, IllegalArgument, NullPointer, take your pick).

If I want to access that via reflections, I would use this (assume instance is a HasCollection):

Field exceptions = HasCollection.class.getDeclaredField("exceptions");
exceptions.setAccessible(true);
List<Class> privateExceptions = new ArrayList<>((List<Class>) exceptions.get(instance));

But this only almost works. Instead of the actual classes that are in the list, instead I get a bunch of com.my.class.hierarchy.InstanceOf instances. Those don't de/serialize properly (using Jackson). Is there anything I can do about that without knowing a priori what classes those instances actually represent?





Get Ambiguous method with enum parameters

I'm trying to invoke a method from a dynamically loaded assembly. The method is ambiguous.

For example: The dll contains the following methods:

public static string ReadString(string key, KeyType type)
public static string ReadString(string key, string type)

I would like to invoke the one with the enum parameter KeyType.

var assembly = Assembly.LoadFile(@"stringutils.dll");
Type type = assembly.GetType("Utils.StringReader");

I tried

var method = type.GetMethod("ReadString", new[] { typeof(string) });

And tried

var method = type.GetMethod("ReadString", new[] { typeof(string), typeof(int) });

But it returns null





Create Delegate from MethodInfo with Output Parameters, without Dynamic Invoke

I am trying to get a Delegate from a MethodInfo object that has Output Parameters. My code follows:

static void Main(string[] args) {

        MethodInfo m = typeof(Program).GetMethod("MyMethod2");

        IEnumerable<Type> paramsTypes = m.GetParameters().Select(p => p.ParameterType);

        Type methodType = Expression.GetDelegateType(paramsTypes.Append(m.ReturnType).ToArray());

        Delegate d = m.CreateDelegate(methodType);

        Action a = (Action)d;

        a();

    }

I'm getting is a System.InvalidCastException: Unable to cast object of type Delegate2$1 to type System.Action in the line that does "Action a = (Action)d". The thing is that I don't know what type to put in Action because I know that the correct type is not String, it is the Output equivalent of String (String&) in compilation.

MyMethod2 has an Output parameter, and I think that is where the problem is because when I test this with MyMethod which as an Input parameter, it works.

public static void MyMethod2(out String outputParameter) {

        outputParameter = "hey";

    }

public static void MyMethod(String inputParameter) {

  //does nothing 
    
}

Also, I know it is easier if I use Dynamic Invoke instead of a normal Delegate call but I'm not interested in that because I'm trying to enhance the performance of my program. Does anyone know how to do this? Thank you





Get Folder Information through Reflection in c# [duplicate]

#Get current Assembly information through Reflection.

protected static string GetCurrentFolder()
{
    string codeBase = Assembly.GetExecutingAssembly().CodeBase;
    UriBuilder uri = new UriBuilder(codeBase);
    string path = Uri.UnescapeDataString(uri.Path);
    return Path.GetDirectoryName(path);
}  




'Expression of type 'System.String' cannot be used for parameter of type 'System.Reflection.PropertyInfo'

I have two classes - ContactCompany and inside List of ContactPeople.

The result must be - list of all contact people or a specific contact person that matches a certain criteria.

The criteria is a string and it will search all the string fields in both classes. If a ContactCompany is found , all the list of contact people will be displayed.

So Far I came up with this:

public List<ContactPersonDto> FilterContragentAndClients(string filter)
{
    var contactCompanyStringProperties = typeof(ContactCompany).GetProperties().Where(prop => prop.PropertyType == filter.GetType() && prop.DeclaringType.Name != "AuditEntity`1");
    var contactPersonStringProperties = typeof(ContactPerson).GetProperties().Where(prop => prop.PropertyType == filter.GetType());
    var together = contactCompanyStringProperties.Concat(contactPersonStringProperties);

    var allContactPersonFoundInCompany = this.contactCompanyRepository.GetAll(cc => contactCompanyStringProperties.Any
        (prop => ((prop.GetValue(cc, null) == null) ? "" : prop.GetValue(cc, null).ToString().ToLower()) == filter)).SelectMany(acc => acc.ContactPeople).ToList();

    var contactPersonOnItsOwn = contactPersonRepository.GetAll(cp => contactPersonStringProperties.Any
        (prop => ((prop.GetValue(cp, null) == null) ? "" : prop.GetValue(cp, null).ToString().ToLower()) == filter));

    var totalList = allContactPersonFoundInCompany.Concat(contactPersonOnItsOwn).Distinct().ToList().Take(100);

    List<ContactPersonDto> result = new List<ContactPersonDto>();
    foreach (var item in totalList)
    {
        result.Add(mapper.Map<ContactPersonDto>(item));
    }
    return result;
}

My idea was to check the property and its value, ToString() it and compare it with the criteria the user has inputted.

Just another note - I wrote the prop.Declarintype.Name in order to exclude AuditEntity properties.(Created By, Created At, etc.)

When I hit allContactPersonFoundInCompany the ToString() cannot be translated.

This is the full error I receive:

Expression of type 'System.String' cannot be used for parameter of type 'System.Reflection.PropertyInfo' of method 'Boolean Contains[PropertyInfo](System.Collections.Generic.IEnumerable`1[System.Reflection.PropertyInfo], System.Reflection.PropertyInfo)' (Parameter 'arg1')




dimanche 21 juin 2020

Some services are not able to be constructed when dynamic assembly loading

I am trying to add assembly by reflection in my .net core project (DNAPI). That external project (EBiletManager) include ILogger and other required services from other common reference project (DNDomain.proj).

public class EBiletManager : DNDomain.IScopedProcessingService {

    ILogger _logger;
    IConfiguration _configuration;

    public EBiletManager(ILogger logger, IConfiguration configuration,

...

When I add the EBiletManager to DNAPI from Project Dependencies, these are working correctly.

I spend hours for this problem and I try this plug-in methods. And I try copy all DLL references to \bin\Debug\netcoreapp3.1 folder but not working.

Assembly loading correctly but "EBiletManager" constractor throw this error.

System.AggregateException

Service description lines:

public static IServiceCollection AddCustomServices(this IServiceCollection services, IConfiguration configuration) {
            services.AddHostedService<TimedHostedService>();

            var loadContext = new PluginLoadContext(pluginLocation);
            var assembly = loadContext.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(pluginLocation)));
            foreach (Type type in assembly.GetTypes()) {
                if (type.GetInterface(nameof(DNDomain.IScopedProcessingService)) != null) {
                    services.AddScoped(typeof(DNDomain.IScopedProcessingService), type);
                }
            }
...

Sorry for bad English and thanks for helps.





using reflection to identify properties that are null or 0 for a web service application

I have a request entity that hits my endpoint. Let's say the entity is RequestEntity. It has certain Props of different types.

public class RequestEntity {
public RequestEntity(){
FriendList = new List<String>();
}

public string Name{get;set;}
public int Age{get;set;}
public FriendList{get;}
}

I want to operate on the entity only when a specific property is present and others are null. Is there any way for me to go through the object without having to write multiple if else blocks to check if only the required field is present and others are not. I thought of using reflection but I think it wont be a good idea as it is a webserver and reflection is slow. can anyone give any references or a better approach for it?





No Function Found on type: org.primefaces.util.ComponentUtils with signature: java.lang.String resolveWidgetVar

I am trying to deploy a multi module ear with several war files in Wildfly container and getting the following error:

No Function Found on type: org.primefaces.util.ComponentUtils with signature: 
java.lang.String resolveWidgetVar(java.lang.String, javax.faces.component.UIComponent)

I am using prime-faces version 5.3 and I decompiled the jar from the libs deployment directory and I can find the function there.

enter image description here

Also, I have tried checking the jar file path for the class ComponentUtils, and it prints the expected path for the 5.3 version class.

Also checked the calling code for the function from the Stacktrace as below:

17:54:24,447 SEVERE [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 88) Critical error during deployment: : com.sun.faces.config.ConfigurationException: java.lang.Exception: No Function Found on type: org.primefaces.util.ComponentUtils with signature: java.lang.String resolveWidgetVar(java.lang.String, javax.faces.component.UIComponent)
at deployment.posa.ear//com.sun.faces.config.processor.FaceletTaglibConfigProcessor.processFunctions(FaceletTaglibConfigProcessor.java:642)
at deployment.posa.ear//com.sun.faces.config.processor.FaceletTaglibConfigProcessor.processTagLibrary(FaceletTaglibConfigProcessor.java:325)
at deployment.posa.ear//com.sun.faces.config.processor.FaceletTaglibConfigProcessor.process(FaceletTaglibConfigProcessor.java:270)
at deployment.posa.ear//com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:441)

The class FaceletTaglibConfigProcessor.java comes from com.sun.faces jsf-impl library which tries to load the ComponentUtils class and call the method by parsing the method signature as below:

enter image description here

The method ReflectionUtil.forName tries to load the class with a specific class loader and I am assuming it is able to load the class (since we get the exception later) but it may be loading this from a different location then from where my code does it. I am assuming something bad happens in class loading and I ain't good at that.

How do I get around this problem. I have tried clearing .m2 cache and build targets and deployment directories but nothing works here.

ReflectionUtil.forName method code:

enter image description here





Calculating water reflection y-coordinates of birds/clouds in a 2d landscape

I am having trouble to calculate the y coordinate for the water reflections of birds/clouds in a 2d landscape. So I think some factors that determine the y_relection are the height (y) and depth (z, although I haven't used 3d) of the cloud/bird and also the viewing angle (but again this is all just 2d drawn sprites). Anyone an idea how I could proceed to calculate the y_reflection in this 2d setup?

enter image description here





Reference Assemblies not loaded from an integration test project dynamically in .Net Core 3.1

I create an integration test project that has a reference to a Rest API project. On the startup of my Api I do some reflection to load some classes I have on other assemblies, but I am not specifying the path of the assembly, I simply add them as a reference on my project and load them on this way

var assemblies = Assembly.GetEntryAssembly()?.GetReferencedAssemblies().Select(Assembly.Load);

When I am running my integration test project, it has a reference to my Rest API project, but it will not load into memory all the references that my Rest Api project has because the main thread is running now from my test project instead of my Rest API. I tried to add a reference to each of the projects into my Integration Test project with the hope that GetReferencedAssemblies was going to include some of them. Also, I tried to client dummy objects inside of my Integration Test Project to have an explicit reference to some of the classes of those assemblies, but when I execute the previous line, I am not getting any of the referenced assemblies(projects)

Any idea of how can I solve this issue?





samedi 20 juin 2020

How to load java class and its reference class recursively

Image The class digram like this:

class A {
  B b;
}

class B {
  C c;
}

class C {
}

I wanna load class A、B and C, but when I try class.forName("A") the JVM only loads class A, how can I load all classes from A to C recursively?





Can I use Reflection to call a method's super method?

I want to call a method's super method using reflection, but my method doesn't work, and I'm not sure it's possible. Here's my method to call the super method for the equals(Object) method of class T, which is also called the targetClass here:

private ToBooleanThrowingBiFunction<T> getSuperEquals() {
  Class<T> targetClass = getTargetClass();
  Class<?> superClass = targetClass.getSuperclass();
  while ((superClass != Object.class) && (superClass != null)) {
    try {
      Method method = superClass.getDeclaredMethod("equals", Object.class);
      return (thisOne, thatOne) -> {
        try {
          return (Boolean) method.invoke(thisOne, thatOne);
        } catch (InvocationTargetException e) {
          throw new IllegalStateException(e.getCause());
        }
      };
    } catch (NoSuchMethodException e) {
      superClass = superClass.getSuperclass();
    }
  }
  throw new IllegalArgumentException(String.format("E10: No superclass of %s has an equals() method.", targetClass));
}

@FunctionalInterface
private interface ToBooleanThrowingBiFunction<T>  {
  boolean eval(T thisOne, T thatOne) throws IllegalAccessException;
}

This code correctly extracts a Method that holds the super.equals() method. But when I call it, it executes the equals() method of the targetClass. Is there a way to do this?





Golang : Dynamic Pointer to Struct is missing Embedded Struct's methods but works without pointer reference

I've 2 structs, Both embedded another struct called Test.

The struct Created at Compile time EmbeddedCompiledStruct is able to access the Method from Test struct. However the Dynamically created Struct is able to access the Method only if it is accessed via the struct but not via its Pointer.

// Test ...
type Test struct {
    Name string
}

// TableName ...
func (Test) TableName() string {
    fmt.Printf("MyTableName called")
    return "MyTableName"
}

// EmbeddedCompiledStruct ...
type EmbeddedCompiledStruct struct {
    Test
}

type tabler interface {
    TableName() string
}

func main() {
    structFields := []reflect.StructField{
        {
            Name:      "Type",
            Type:      reflect.TypeOf(Test{}),
            Tag:       `json:"-" gorm:"-"`,
            Anonymous: true,
        },
        {
            Name: "Name",
            Type: reflect.TypeOf(""),
            Tag:  `json:"name,omitempty" gorm:"column:Name;not null;size:16;primary_key"`,
        },
    }
    
    structDec := reflect.StructOf(structFields)
    compiledStruct := reflect.TypeOf(EmbeddedCompiledStruct{})

    // Normal Structs 
    fmt.Printf("\nType Dynamic Embedded Struct Methods : %+v\n", structDec)
    for i := 0; i < structDec.NumMethod(); i++ {
        fmt.Println(structDec.Method(i).Name)
    }
    fmt.Printf("\nType Compiled Embedded Struct Methods : %+v\n", compiledStruct)
    for i := 0; i < compiledStruct.NumMethod(); i++ {
        fmt.Println(compiledStruct.Method(i).Name)
    }
    
    // Pointer to Structs
    t1 := reflect.TypeOf(reflect.New(structDec).Interface())
    fmt.Printf("\nType Dynamic Embedded Struct Pointer Methods : %+v\n", t1)
    // -----> Here its missing TableName Method
    for i := 0; i < t1.NumMethod(); i++ {
        fmt.Println(t1.Method(i).Name)
    }

    t3 := reflect.TypeOf(reflect.New(compiledStruct).Interface())
    fmt.Printf("\nType Compiled Embedded Struct Pointer Methods : %+v\n", t3)
    for i := 0; i < t3.NumMethod(); i++ {
        fmt.Println(t3.Method(i).Name)
    }

    fmt.Println("")
    if tabler, ok := reflect.New(structDec).Interface().(tabler); ok {
        fmt.Println("Convertible Dynamic Struct " + tabler.TableName())
    } else {
        fmt.Println("Not convertible Dynamic Struct")
    }

    if tabler, ok := reflect.New(compiledStruct).Interface().(tabler); ok {
        fmt.Println("Convertible Compiled Struct " + tabler.TableName())
    } else {
        fmt.Println("Not convertible Compiled Struct")
    }
}

Output:

Type Dynamic Embedded Struct Methods : struct { Type main.Test "json:\"-\" gorm:\"-\""; Name string "json:\"name,omitempty\" gorm:\"column:Name;not null;size:16;primary_key\"" }
TableName

Type Compiled Embedded Struct Methods : main.EmbeddedCompiledStruct
TableName

Type Dynamic Embedded Struct Pointer Methods : *struct { Type main.Test "json:\"-\" gorm:\"-\""; Name string "json:\"name,omitempty\" gorm:\"column:Name;not null;size:16;primary_key\"" }

Type Compiled Embedded Struct Pointer Methods : *main.EmbeddedCompiledStruct
TableName

Not convertible Dynamic Struct
MyTableName calledConvertible Compiled Struct MyTableName

The t1 Object doesn't Print the method name TableName. However the object created from Compiled Struct works fine in both scenario's even though they embed the same struct.

Why is DynamicStruct Pointer not able to Get the Embedded Methods but a Compiled Struct is able to do it? Is this a bug of some sort in Golang?

Playground : https://play.golang.org/p/zrWP0WfL9lQ





Is it possible to provide a Name to a Dynamically created Struct (using Reflection) in Golang

I've a dynamically created struct and I would like to provide a Name to this struct. Is it possible to do that?

// Test ...
type Test struct {
    Name string
}

func main() {
    structFields := []reflect.StructField{
        {
            Name: "Name",
            Type: reflect.TypeOf(""),
        },
    }
    // Provide a Name to this structDec 
    structDec := reflect.StructOf(structFields)

    fmt.Printf("\nType Dynamic : %+v\n", structDec)
    fmt.Printf("\nType Test : %+v\n", reflect.TypeOf(Test{}))
}

This prints

Type Dynamic : struct { Name string }

Type Test : main.Test
  1. Is it possible to set a Name such as Test1 to the Dynamic Struct structDec?
  2. How does go derive the struct Name? I see during dynamic struct creation the str value (which is the same value in the output) is set in reflect.structType, Is this how the Name is calculated for Dynamic Struct's?

Go Playground : https://play.golang.org/p/8ra2pXZIHgp





how to get the class name at run time from a generic method that is in another class?

I am trying to generate my baseurl using UriBuilder. I have created a generic "GetRequestUrl" which is in my TestUtil class. How can I get the name of my Test class at run time using this method and append to the string serviceAPI

//Here is the GetRequestUrl method in my TestUtil class

public class TestUtil
{
        public string GetRequestUrl(string serviceName)
        {
            string serviceAPI = this.GetType().BaseType.Name;
            var requestUrl = new UriBuilder();
            requestUrl.Scheme = "http";
            requestUrl.Host = "svc-" + serviceName + "." + 
       ConfigurationManager.AppSettings["TestEnvironment"] + "-example.com/api/";
            requestUrl.Path = serviceAPI;
            Uri uri = requestUrl.Uri;

            return uri.ToString();

        }
}

//Here is my Test class where I want the Class name "TestClass" to append to serviceAPI string at run time, but I am getting TestUtil. I have tried following..

this.GetType().Name;

this.GetType().BaseType.Name;

MethodBase.GetCurrentMethod().DeclaringType.Name;

public class TestClass
{
TestUtil util = new TestUtil();
    [Test]
    public void Method1()
{
     string fullUrl = util.GetRequestUrl("APIServiceName");

}

}




vendredi 19 juin 2020

Difference between GetEntryAssembly and GetExecutingAssembly

I've read docs for GetEntryAssembly and GetExecutingAssembly trying to make sense of the difference between them. I simply fail to understand how the definitions relate to each other. Altough I see two different formulations, I can't understand the distinction implied. In my head, it's a potayto-potahto situation, which is reinforced by the same contents on my screen when I try to display the values of each returned Assemby object.

Naturally, there must be some difference and it's simply my comeptense that prevents me from realizing what it is. So I've done some research, only discovering that most of the wisdom out there is about obtaining the path. The lonely resource that was explictly targetting the comparison between them was a dead link.

Can I ask for a specific example where those two methods return objects the contents of which differ? Preferably with a brief explanation of why.





jeudi 18 juin 2020

Can't invoke Method

I'm running the following and getting this error bellow. it seams to be a problem with invoke but I don't see anything that can cause it appreciate the help.

        Class<?> eventClass;
        long delayTime = restart.timeList.get(i);
        try {
            eventClass = Class.forName(restart.eventList.get(i));
            Method runMethod = eventClass.getMethod("run");
            //Method runMethod = eventClass.getDeclaredMethod("run");
            //Object runEvent = runMethod.getParameterTypes();
            System.out.println(runMethod.getName());
            System.out.println(runMethod.getDeclaringClass());
            runMethod.invoke(eventClass);
        }

        catch (ClassNotFoundException | NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

Output:

[com.COMP308.TME4.ThermostatNight, com.COMP308.TME4.LightOn, com.COMP308.TME4.WaterOff, com.COMP308.TME4.ThermostatDay, com.COMP308.TME4.Bell, com.COMP308.TME4.WaterOn, com.COMP308.TME4.LightOff, com.COMP308.TME4.Terminate, com.COMP308.TME4.FansOn, com.COMP308.TME4.FansOff]
run
class com.COMP308.TME4.ThermostatNight
Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at com.COMP308.TME4.EventReflextion.main(EventReflextion.java:33)




Access to virtual method table

I have a mono.cecil based lib where I need to find all implementations of some virtual method X. The thing is that the method X is different each time. It could be any virtual methods. I think it could be possible only if vtable is available somehow. Because the methods like Equals(...) could have hundreds of implementations. If it helped, I would be fine to limit the search by some certain assembly.

The only way I see now is described below:

  1. Get DeclaringType of the virtual method.
  2. Find all inherited types in the assembly.
  3. Analyze each type if it has an implementation for the method.

The approach is not optimal. Even if I added some cache, it would still be so slow because of assembly analysis but the execution path is critical. If you see any other solution, please share it.





Get DateTime value From FieldInfo

I am tryning to retrieve a DateTime via reflection. The value is not inside a class or a static class, but it is from a lambda expression...

I have this really simple lambda expression: ATest => ATest.MyDate == DateTime.Now

Now, via an ExpressionVisitor I am trying getting datetime value:

public class ExpressionComparionsVisitor : ExpressionVisitor
{
    public Expression Modify(Expression expression)
    {
        return base.Visit(expression);
    }


    protected override Expression VisitMember(MemberExpression node)
    {
        if (node.NodeType == ExpressionType.MemberAccess)
        {
            if (node.Member.MemberType == System.Reflection.MemberTypes.Field)
            {
                if (node.Type ==  typeof(DateTime))
                {
                    System.Reflection.FieldInfo fieldInfo = node.Member as System.Reflection.FieldInfo;

                    if (fieldInfo != null)
                    {
                        //Here what I have tried, but no success

                        //var n = (DateTime)fieldInfo.GetValue(fieldInfo);
                        //var n = (DateTime)fieldInfo.GetValue(typeof(DateTime));
                        //var n = (DateTime)fieldInfo.GetValue(node.Member);
                        //var n = (DateTime)fieldInfo.GetValue(null);
                    }
                }
            }
        }
            return base.VisitMember(node);
    }
}

How can I get the DateTime value of that field? Thank you





c# 8 nullability - generic class "knowing" its nullability

I've got two classes - an inner class and an outer class, where the inner class can return a null value and an outer class that shouldn't (assuming, of course, that the type parameter T represents a non-nullable type):

#nullable enable
public class Insider<T>
{
    [MaybeNull, AllowNull]
    public T Value {get; set; }

    public Insider()
    { Value = default; }
}
public class Outsider<T>
{
    Insider<T> Inside = new Insider<T>();

    public T Value
    {
        get
        {
            return Inside.Value; // Compiler warning "'Value' may be null here"
        }
        set { Inside.Value = value; }
    }
}
public class Fred
{ }
public static class Test
{
    public static void Stuff()
    {
        Outsider<Fred> one = new Outsider<Fred>();
        Debug.WriteLine("one.Value is " + one.Value);

        Outsider<Fred?> two = new Outsider<Fred?>();
        Debug.WriteLine("two.Value is " + two.Value);

        Outsider<int> three = new Outsider<int>();
        Debug.WriteLine("three.Value is " + three.Value);
    }
}
#nullable disable

When I run this, it gives the expected output:

one.Value is
two.Value is
three.Value is 0

The program state that causes "Insider.Value" to be null is a specific error state, and the caller should know the system is in that state and not access "Outsider.Value", which means that caller should never see "Outsider.Value" return null, but I'd like to enforce that.

And yes, both classes should handle structs as well as classes.

What I was thinking, was something along these lines:

public class Outsider<T>
{
    Insider<T> Inside = new Insider<T>();

    public T Value
    {
        get
        {
            if ((Inside.Value == null)&&(T_shouldnt_be_null))
                throw new Exception("Nope");
            return Inside.Value;
        }
        set { Inside.Value = value; }
    }
}

The troublesome part, of course, is the "T_shouldnt_be_null".

If I put more debugging in Outsider.Value:

public class Outsider<T>
{
    Insider<T> Inside = new Insider<T>();

    public T Value
    {
        get
        {
            Type? nullableType = Nullable.GetUnderlyingType(typeof(T));
            Debug.WriteLine("      typeof(T) is "  + typeof(T) + "; nullableType=" + ((nullableType==null)?"null": nullableType.ToString()));
            foreach (var x in typeof(T).CustomAttributes)
                Debug.WriteLine("         " + x);
            return Inside.Value;
        }
        set { Inside.Value = value; }
    }
}

I get results that were not what I expected. The results when the type parameter T is Fred (non-nullable) are:

typeof(T) is BTSDataCollator.Fred; nullableType=null

and the results when the type parameter is Fred? (nullable) are:

typeof(T) is BTSDataCollator.Fred; nullableType=null

The compiler has completely stripped the nullability indicator from the type. And in both cases the class type has no CustomAttributes (and that's what this post relies on to determine nullability)

Is there any way that a (generic) class can get information on the nullability of its actual type parameter (Fred vs. Fred?) ?





Java Proxy and Vaadin throws NullPointerException

I am attempting to register a ClickListener to a Button. I am using Vaadin 8. This listener should be implemented using Proxy.

final Button button = new Button("Hello");

final Class<?> clickListenerClass = Button.ClickListener.class;
final Object clickListenerInstance = Proxy.newProxyInstance(clickListenerClass.getClassLoader(),
    new Class[] {clickListenerClass}, (proxy, method, args) -> {
        System.out.println("TEST");

        return null;
    });

button.addClickListener((Button.ClickListener)clickListenerInstance);

Here is the stack trace (I have omitted my code. The exception occurs on the last line of the above snippet).

java.lang.NullPointerException: null
    at com.sun.proxy.$Proxy20.hashCode(Unknown Source)
    at com.vaadin.event.ListenerMethod.hashCode(ListenerMethod.java:571)
    at java.util.HashMap.hash(HashMap.java:339)
    at java.util.HashMap.put(HashMap.java:612)
    at java.util.HashSet.add(HashSet.java:220)
    at com.vaadin.event.EventRouter.addListener(EventRouter.java:64)
    at com.vaadin.server.AbstractClientConnector.addListener(AbstractClientConnector.java:842)
    at com.vaadin.ui.Button.addClickListener(Button.java:333)




How to use quasiquotes with previously defined object

I just started studying scala compile-time reflection, and I got introduced to quasiquotes by the Scala official guides.

One concept I'm still struggling with is how am I supposed to work with quasiquotes (or reify, for that matter) if I want to generate the AST for an already defined object. Suppose I have an Object:

object MyObject {
  def method1() = "m1"
}

In order to get a tree, I know I can do

q"""{object MyObject {
  def method1() = "m1"
}}
"""

Doing this, however, prevents me from having the object actually defined in my scope (and I also need to define it entirely inside a String, throwing all code safety out of the window).

What I'd like to do to get that tree is something like this:

object MyObject {
  def method1() = "m1"
}

q"$MyObject" // or q"{MyObject}", I still don't fully understand the table on the Scala guide

I want to define the object, and, afterwards, use that definition to perform some checks over it (and throw some exception in compile-time, if need be), using a macro. To use a macro, I'll need to tree (or, at least, the expression), as far as I understood.

I already know how to do the checks I want using Scala reflection in run-time, but I thought using ASTs could be a good idea (and, on the process, I would learn something). I'm getting the feeling that I'm misunderstanding some basic concept on how to use ASTs, though - it seems like one can generate ASTs based on code declared on the call site only. I'm confused.

What am I misunderstanding here?





Get class properties from class absolute path using reflection in java

im generating new classes using file package but when i want to get the class properties using reflection it doesn't work and it gave me the error bellow but when i refresh my package by clicking on the right button of my mouse and i click on refresh and i rerun my function it works. So now i think that i need to change my method to get those properties by using absolut path instead of name of package.

my code

import java.lang.reflect.Field;

public class Main7{
    public static void main(String[] args) throws Exception {

        Class classe = Class.forName("com.test.model.Client");
        // affiche tous les attributs
        System.out.println("Attributs -------------------------------------");
        for (Field attribut : classe.getDeclaredFields()) {
           // System.out.print("   "+Modifier.toString(attribut.getModifiers()));
            String type = attribut.getType().getName();
            if(type.contains(".")) {
                String[] tab = type.split("\\.");
                type=tab[2];
            }
            System.out.println(type+" "+attribut.getName());
        }

    }
}

error

Exception in thread "main" java.lang.ClassNotFoundException: ma.dxc.generator.model.Clientz
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at generatortest.Main7.main(Main7.java:16)

good result

Attributs -------------------------------------
long id
String name
String city




Network printer reflection from WLAN repeater to base station router

I've an old hp LaserJet 4100 Series network printer connected to a FritzBox! 7390 in function as an WLAN repeater, because I don't want to lay a LAN cable across two rooms to the base station router (FritzBox! 7530).

The problem is, that I want to use the WLAN from the base station router, but the printer isn't directly connected to it. So I must change the WLAN (from FritzBox! 7530 to FritzBox! 7390) before printing a document. That's very annoying and not a good usability.

So my question is: Is it possible to reflect a network printer from a WLAN repeater to the base station router within the same network, so I can print in every WLAN? I've searching for it in the internet, but no good answer found. Can you help me?





Instead of using reflection to loop though a class properties, can i serialize it to json string and look through it? Are there any downsides to it?

Assume I have a class as below

class Student
{
    public int ID { get; set; }

    public string Name { get; set; }
}

Just with 0 more properties.I want to loop through these properties. I can do it through reflection, which will have a performance cost. Is serializing it using Newtonsoft JSON and looping through it better?





how to print a collection as valid code in scala

Assume I have

val x = List("a","b","c")

I'd like to have a function f which when called, returns

List("a","b","c")

Currently, println(x) just prints List(a,b,c) which will not compile when compiled/pasted into an Scala-Notebook or Unit-Test.

I'm stuck to find a general solution which also works for Seq[Double] etc , I managed to get something for Seq[String] by re-adding the quotes, but I'm unable to get a proper solution for all collection types





NetCore InputTagHelper using reflection

I have a model with lots of properties. Creating or updating theirs views is a troublesome work.

So i trying to use Reflection to create view during runtime: (PS: yes, i know the front-end is very import, i should use Vue or other frame to create views at designtime. But I just want to try buildering forms at runtime, yes i am a freak. LOL)

There is my code:

@{
    var dic = Model.GetAttributePropsByCategory();// get PropertyInfo by CategoryAttribute and custom DisplayIndexAttribute
}
@foreach (var items in dic)
{
    var category = items.Key; //  InfoCategoryAttribute
    foreach (var tuple in items.Value)
    {
        var displayIndex = tuple.Item1; // Custom: DisplayIndexAttribute
        var prop = tuple.Item2; // PropertyInfo

        <input asp-for="@prop.Name" class="form-control"/>
    }
}

My target is:

<input class="form-control valid" type="text" data-val="true" data-val-required="The VIN field is required." id="VIN" name="VIN" value="VIN001" aria-describedby="VIN-error" aria-invalid="false">

But the result like this:

<input class="form-control valid" type="text" data-val="true" data-val-required="The Name field is required." id="prop_Name" name="prop.Name" aria-describedby="prop_Name-error" aria-invalid="false">

So, I read the source code in the aspnetcore.mvc.taghelpers. I found the key is InputTagHelper.For:

public class InputTagHelper : TagHelper
{
    ...

    [HtmlAttributeName(ForAttributeName)]
    public ModelExpression For { get; set; }

    ...
}

But I can't understand how the InputTagHelper.For was created. Therefor, i dont know how to override it to achieve my target.

Is there any Suggestions? Thx.





Create an object using Expression Trees without generic arguments

I have a class that is a bit like the following

public class SpecialList<T> : List<T>
{
    public SingleOrList() { }
    public SingleOrList(IEnumerable<T> list) : base(list) {}
    ...
}

When converting it from JSON, it can be turned into this special list as either a single object, or an array of that object in the following manner.

...

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    var token = JToken.Load(reader);

    if (token.Type == JTokenType.Array)
    {
        var originalList = token.ToObject(objectType.BaseType, serializer);
        return Activator.CreateInstance(objectType, originalList);
    }

    var list = (IList) Activator.CreateInstance(objectType);
    var genericType = objectType.GetGenericArguments().Single();
    var single = token.ToObject(genericType, serializer);

    list.Add(single);

    return list;
}

Ignoring the fact of whether or not this is a good idea for the moment, I was interested in whether you could use / how you would use complied expression trees here instead of Activator.CreateInstance to create the classes.

Most of the examples I've seen use generics which is not possible for me here as I don't know up front the generic type, e.g.

public static Func<T> Instance = Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile();




mercredi 17 juin 2020

How to use the where clause with IQueryable

I am using Entity Framework Core with reflection to generate some forms dynamically. Everything is working except the WHERE Clause. I get the following error:

An expression tree may not contain a dynamic operation

I am able to fix this by converting my IQueryable to a List, but that introduces different problems that i would like to avoid.

Here is my code:

public async void ViewCollection(PropertyInfo propertyInfo)
{
    Type propertyType = propertyInfo.PropertyType;
    InversePropertyAttribute inversePropertyAttribute = (InversePropertyAttribute)ReflectionHelpers.GetAttribute(propertyInfo, typeof(InversePropertyAttribute));


    //GET THE TYPE OF THE COLLECTION
    Type collectionType = propertyInfo.PropertyType.GenericTypeArguments[0];

    //GET THE INVERSE PROPERTY INFO
    PropertyInfo inverseProperty = collectionType.GetProperty(inversePropertyAttribute.Property);

    //GET THE FOREIGN KEY ATTRIBUTE FROM THE INVERSE PROPERTY
    ForeignKeyAttribute foreignKeyAttribute = (ForeignKeyAttribute)ReflectionHelpers.GetAttribute(inverseProperty, typeof(ForeignKeyAttribute));

    //GET THE FOREIGN KEY PROPERTY FROM THE FOREIGN KEY ATTRIBUTE
    PropertyInfo foreignKeyProperty = collectionType.GetProperty(foreignKeyAttribute.Name);

    //GET INCLUDED TYPE NAMES BY FOREIGN KEY
    IEnumerable<string> includedTypes = collectionType.GetProperties().Where(p => p.PropertyType.IsClass).Where(p => ReflectionHelpers.HasAttribute(p, typeof(ForeignKeyAttribute))).Select(r => r.Name);

    //GET THE DATA SET
    IQueryable<dynamic> items = ReflectionHelpers.GetDbCollectionByType(Db, collectionType);

    //INCLUDE THE INCLUDED TYPES BY NAME
    foreach (string includedType in includedTypes) items = items.Include(includedType);

    //THIS IS WHERE THE ERROR IS
    items = items.Where(i => foreignKeyProperty.GetValue(i, null) == PrimaryKeyProperty.GetValue(Item, null));

    await ShowCollection(collectionType, items, propertyInfo.Name);
}

How can i solve this with out changing my type to a list?





How to use reflection on a COM object exposed through a RCW?

I used the Type Library Importer (TlbImp.exe) to generate an interop assembly for interfacing with a COM object. Something I am trying to do is build an expression tree that calls a method on a COM object. I want to compile the expression tree into a lambda and cache it.

The reason I want to do this is because in this COM object, there are many similar interfaces where the only thing that changes is the parameter type. For example, there is an interface for IFooDouble, IFooInt, IFooString, IFooLongInt, etc. Then each one will define a method SetValue(T value) where T will be either double, int, string, etc., depending on the interface. Here I would compile an expression tree into an Action<IFooBase, T> lambda and cache it.

The generated interop assembly contains strongly typed interfaces to the SetValue method, but I cannot find a way to get a reference to it's MethodInfo object through reflection. Since the wrapper type is System.__ComObject, I can call InvokeMember and do it that way. However, I am wondering if it will be much slower than if I were to call the method directly through one of the interop interfaces? That is, I am wondering if IFooBase.InvokeMember("SetValue", ...) is going to have much worse performance over IFooDouble.SetValue(11.3), especially when doing many repeated calls.





Assign value to setter method using reflection

How do i create object at runtime and set values all the setter values in the object ? I am generating below classes at runtime using jsonschema2pojo.Classes field can change ,

class Foo
(

int a ;
int b;

List <Abc> list;
//getters and setter ommited
}

class Abc
{

int c ;
int d;

}




Scala class constructor lot of fields

I have a class with a primary constructor that takes more than 50 fields:

class HBaseEve   (val rowKey: String,
                 ...
                  val customer: String,
                 ...
                  val managedEntityKey: String,
                 ...
                  val withdrawalReasonForWithdrawal: String)

In my companion object, I declared a method called parse to create a HBaseEve object from a record in HBase table:

    object HBaseEve {
final val COLUMN_FAMILY = "cr"
  override def parse(result: Result): HBaseEve  = {
    if (result.getRow != null)
      new HBaseEve   (
        Bytes.toString(result.getRow),
      ...
        Bytes.toString(result.getValue(HBaseEve.COLUMN_FAMILY.getBytes(), "customer".getBytes())),
        ...
Bytes.toString(result.getValue(HBaseEve.COLUMN_FAMILY.getBytes(), "managedEntityKey".getBytes())),
        ...
        Bytes.toString(result.getValue(HBaseEve.COLUMN_FAMILY.getBytes(), "withdrawalReasonForWithdrawal".getBytes()))
      )
    else null
  }

However, this method parse is not very elegant because I have more than 50 fields in my class to fill in manually. I do not have any idea how to replace this method parse by other method more efficient and profissional.

Any idea on this? I searched about scala.Reflection but i do not have any ideia how to use this. Anyway, i am open to any ideias please.

Thank you





Get the TYPE of a Collection using reflection [duplicate]

In this situation I am passing a propertyInfo that I know is an ICollection.

How can get the type of the class that the collection is of?

Type propertyType = propertyInfo.PropertyType;
Type collectionType = ????????




Retrieving a collection from a generic method with a run time generic type

I have a generic method

var propertyResolverMethod = _propertyResolver
    .GetType()
    .GetMethod(
        nameof(_propertyResolver.GetEntities),
        new[] { typeof(string), typeof(string) })
    ?.MakeGenericMethod(_itemType);

and the invocation

var recommendedItems = propertyResolverMethod
    ?.Invoke(
        _propertyResolver,
        new object[] { itemId, ResolvedCollectionId });

It on the compile-time it returns an object, but on runtime, it returns IQueryable<Item> this item is the item from _itemType and we find out its type only on runtime, but I know that it has a collection inside Item.RelatedItems that I need to get. Tried already casting to dynamic, but does not work for my case, I know that's somehow solvable via Expressions.

Should be iteratable like this

var itemIds = recommendedItems?.Select(i => i.RelatedItems.Select(s => s.ItemID));

But it's not possible without a proper cast





mardi 16 juin 2020

Can a class library reflectively access packages outside of itself when added to a project?

I'm making a very basic ORM using Spring JDBC. The very foundation of it works by giving it a package name containing entities as part of a YAML config file which it then scans using the Reflections library and generates RowMapper implementations for each of them using ByteBuddy. This works perfectly when running my tests directly from my ORM class library. The issue arises when adding my ORM class library as a maven dependency to another project (as one would do for Spring Data JPA for example). I have moved my entities from the ORM project itself to the separate test project and, ever since doing this, Reflections cannot find the entities (nor the package by the looks of things).

My question is this : Is it even possible for a class library to (reflectively) find packages/classes outside of itself when added as a dependency to another project? If not, how does Spring Data JPA work?





Comparing 2 struct at run time

I'm trying to compare 2 struct at run time. I can't seem to compare the field one by one. I'm thinking i would need to cast the type for each field while running my loop but reflect.TypeOf() doesn't give me expected result of "type" ( int / string in that case ). I'm thinking it's because i'm providing an interface{} as an argument? is there any way to make it work ?

My goal is to be able to compare value from 2 structs of the same type and " merge " the values into one struct if there's any differences.

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    Foo string
    Bar int
    Zoo int
}

func main() {
    a := &A{Foo: "qwer",Bar:1}
    b := &A{Foo: "zxcv",Bar:1}
    testRefactor(a,b)

}

func testRefactor(t *A,comp *A) {
    valt := reflect.ValueOf(t).Elem()
    //valComp := reflect.ValueOf(comp).Elem()
    for i:=0; i<valt.NumField();i++{
        //fieldStructComp := valComp.Type().Field(i).Name
        fieldStructT := valt.Type().Field(i).Name


    valueStructComp := getFieldValueByname(comp,fieldStructT)
    valueStructT := getFieldValueByname(t,fieldStructT)

    typex := reflect.TypeOf(valueStructT)
    fmt.Println(typex.String())

        fmt.Println(valueStructT)
        fmt.Println(valueStructComp)
        fmt.Println(valueStructT == valueStructComp)

    }
}

func getFieldValueByname(structName interface{},fieldname string) interface{} {
    r := reflect.ValueOf(structName)
        f := reflect.Indirect(r).FieldByName(fieldname)
       return f
}