lundi 30 novembre 2020

I can't create a new instance of a ClassMirror by calling the defaullt constructor

I have two classes

class ESVAPI extends BibleProvider {
  ESVAPI() : super('esvapi', true, {'esv'});

 ...methods
}
abstract class BibleProvider {
  ...fields

  BibleProvider(this.name, this._requiresKey, this._versions) {
    Bible.addProvider(this, _versions.toList());
  }
}

I intend to have multiple classes extend the abstract class, so I want to create a method that creates an instances of each of BibleProvider's subclasses, I created one here:

  ClassMirror classMirror = reflectClass(BibleProvider);
  List<DeclarationMirror> subClassMirrors = currentMirrorSystem()
      .libraries
      .values
      .expand((lib) => lib.declarations.values)
      .where((lib) {
    return lib is ClassMirror &&
        lib.isSubclassOf(classMirror) &&
        lib != classMirror;
  }).toList();
  DeclarationMirror subClassDec = subClassMirrors[0];
  ClassMirror ESVCLASS = reflectClass(subClassDec.runtimeType);
  var esvObj = ESVCLASS.newInstance(const Symbol(''), []);

But on ESVCLASS.newInstance I receive this exception:

No constructor '_ClassMirror' declared in class '_ClassMirror'

I'm thinking that this may have to do with how I call the superclass in the Constructor with "hard coded" values. If this is the case, is there a way to call the subclass' constructor and have it call the super constructor? I'm not entirely sure. Anyone familiar with reflections know what may be the case?





relate toString with object creation

I have a fairly basic Java class with some class variables. I have overwridden toString() to provide me with a string output (which will eventually be output to a text file).

I am trying to elegantly create a way for me to use this string output to recreate the object with all of the variables set as before. The class looks something like this:

public class Report {

    private String itemA;
    private String itemB;
    private String itemC;

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Items are::");
        sb.append("\nItem A is: ").append(itemA);
        sb.append("\nItem B is: ").append(itemB);
        sb.append("\nItem C is: ").append(itemC);
        return sb.toString();
    }
}

this is how I can potentially tackle it using reflection:

public class Report {

    private String itemA;
    private String itemB;
    private String itemC;

    private final Map<String, String> MAPPING = new HashMap<>();

    public Report(String itemA, String itemB, String itemC) {
        this.itemA = itemA;
        this.itemB = itemB;
        this.itemC = itemC;

        MAPPING.put("Item A is: ", "itemA");
        MAPPING.put("Item B is: ", "itemB");
        MAPPING.put("Item C is: ", "itemC");
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Items are::");

        MAPPING.entrySet().forEach(entry -> {
            sb.append("\n").append(entry.getKey()).append(BeanUtils.getProperty(this, entry.getValue()));
        });

        return sb.toString();
    }


    public Report createReportFromString(String reportString) {
        List<String> reportLines = Arrays.asList(reportString.split("\n"));
        HashMap<String, String> stringObjectRelationship = new HashMap<>();
        
        reportLines.forEach(reportLine -> {
            Optional<String> matchingKey = MAPPING.keySet().stream().filter(reportLine::contains).findFirst();
            matchingKey.ifPresent(key -> {stringObjectRelationship.put(MAPPING.get(key), reportLine.split(key)[1]);});
        });
        
        stringObjectRelationship.forEach((variableName, variableValue) -> BeanUtils.setProperty(this, variableName, variableValue));
        return this;
    }
}

I basically want to relate the key in the report ("Item A is: ") to the name of the corresponding variable ("itemA") and use this relationship in both the toString() method and the createReportFromString(String string) method. Now when doing this there are a lot of possible exceptions that can be thrown and need to either be handled or thrown - and it then looks a lot less elegant than I would like.

I don't know if this is possible to do without reflection - or perhaps I could rearrange this class to make this possible?

What I can`t change is the structure of the string output in the toString().





MethodInfo.Invoke method with two ref parameters doesn't work [duplicate]

Bellow, you'll find a full running console program that is using Reflection to call a static "Sawpping References" method.

First you have a direct call to the static method, this one is working well. Second you have a invoke call to the same method...

namespace MethodInfoInvoke
{
  using System;
  using System.Globalization;
  using System.Reflection;

  public interface IMyClass<T>
  {
    int Id { get; set; }
    string Name { get; set; }
  }

  public class MyClass : IMyClass<MyClass>
  {
    #region Properties
    public int Id { get; set; } = -1;
    public string Name { get; set; } = default;
    #endregion

    public static void Swap(ref MyClass instance1, ref MyClass instance2)
    {
      MyClass instanceTmp = instance1;

      instance1 = instance2;
      instance2 = instanceTmp;
    }
    public override string ToString()
    {
      return string.Format(CultureInfo.InvariantCulture, "{0} (Id : {1} * Name : {2})", GetType(), Id, Name);
    }
  }

  class Program
  {
    public static void Test1()
    {
      MyClass i1 = new MyClass()
      {
        Id = 1,
        Name = "Name 1"
      };
      MyClass i2 = new MyClass()
      {
        Id = 2,
        Name = "Name 2"
      };

      Console.WriteLine("Test1\r\n\tBefore Swap ref\r\n\t\ti1 : {0}\r\n\t\ti2 : {1}", i1, i2);
      MyClass.Swap(ref i1, ref i2);
      Console.WriteLine("\tAfter Swap ref\r\n\t\ti1 : {0}\r\n\t\ti2 : {1}\r\n", i1, i2);
    }

    public static void Test2<T>() where T : IMyClass<T>, new()
    {
      T i1 = new T()
      {
        Id = 1,
        Name = "Name 1"
      };
      T i2 = new T()
      {
        Id = 2,
        Name = "Name 2"
      };

      Console.WriteLine("Test2\r\n\tBefore Swap ref\r\n\t\ti1 : {0}\r\n\t\ti2 : {1}", i1, i2);
      //
      // ?????????? Here is the problem ! Are references bad ???????
      MethodInfo method = typeof(T).GetMethod("Swap", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod);
      object[] parameters = { i1, i2 };
      method.Invoke(null, parameters);
      //
      //
      Console.WriteLine("\tAfter Swap ref\r\n\t\ti1 : {0}\r\n\t\ti2 : {1}\r\n", i1, i2);
    }

    static void Main(string[] args)
    {
      Test1();
      Test2<MyClass>();
      Console.ReadLine();
    }
  }
}

The goal is to create a "generic" unit test that can be call for all object inheriting from "MyClass".

Thx for your return (and solution :-) ) and sorry for my bad English.





dimanche 29 novembre 2020

Getting an Object by reference in Java

New to this website, and excited to share my first question :)

Ok so I'm going to be explaining what I have set-up currently so that my question can be understood better.

I have 2 java applications:

  1. Logic Application (Where all the heavy load occurs)
  2. Instrumented Application (Application instrumented into a running game)

What I do with these 2 applications is extract information from a game using the Instrumented Application then send it to the Logic Application. The extraction of information/data is done through the Java Reflection API. Then after the information has been extracted, it is sent to the Logic Application through RMI (more on this below).

The reason I have 2 applications instead of 1 is because the game runs on Java 7 (old game), so the Instrumented Application runs on Java 7, and I can run the Logic application on whatever java version I want.

The way I transfer data/information between the 2 is through RMI (Remote Method Invocation). Explanation: The Logic application invokes a getter method at the Instrumented App, and the method uses the Reflection API to grab the field value from the game it's instrumented into and return it.

Now as you guys have understood what I'm basically doing, now comes the challenge that I have been bamboozled by for quite some time.

Problem:

Most of the Field Values that are returned by Reflection are Serializable, therefore they pass-through RMI with no problem. But, some are Un-serializable objects like for an example "Item". "Item" is an object and it holds 3 values: ID, Name, Quantity. So my thought was to make a wrapper and send the wrapper and it would be problem solved right? but no, another challenge popped up.

The challenge that popped up was: What if I needed to know the quantity of the object "Item" that I pulled out at another time? If my whole thing was 1 application, I would've used the Reflection API to get the Field using the Object by: getClassLoader().loadClass("ItemClass").getDeclaredField("Item").get(ObjectThatIPreviouslyFetched); But since I have to transfer the objects over to the Logic Application, I cannot transfer the Object itself "Item" so I have no way to return to that object and get updated information unless I look for the object again which is a waste of resources and makes my whole process slower.

Applications work like so:

Instrumented App -> Reflection -> Game -> Field Value (Object called Item) -> Wrapper -> RMI -> Logic Application (Object information is sent but Object itself can't be sent due to it being unserializable)

Summary of the question (using the pointers just above): How can I get the Object (Item) back so I can get updated information about it using Reflection.

This is the method I made to get the Field Values (Objects):

   /**
    *
    * @param params owner;fieldName;multiplier
    * @param object null if static
    * @return returns the value of the object provided.
    */
   public Object getFieldValue(String params, Object object) {
       String[] paramsSplit = params.split(";");
       try {
           Class<?> clazz = classLoader.loadClass(paramsSplit[0]);
           Field field = clazz.getDeclaredField(paramsSplit[1]);
           field.setAccessible(true);
           Object o = field.get(object);
           if(!paramsSplit[2].equals("0")) return getMultipliedValue((Number) o,paramsSplit[2]);
           else return o;
       } catch (IllegalAccessException | NoSuchFieldError | ClassNotFoundException | NoSuchFieldException e) {
           e.printStackTrace();
       }
       return null;
   } 

This method is found in the Logic Application and it attaches the Instrumented Application to the running game:

    public void inject() {
        VirtualMachine vm = null;
        try {
            vm = VirtualMachine.attach(String.valueOf(pid));
            vm.loadAgent(Info.baseLocation());
        } catch (AttachNotSupportedException | IOException |
                AgentLoadException | AgentInitializationException e) {
            e.printStackTrace();
        } finally {
            try {
                if(vm != null) vm.detach();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

I hope everything was understandable, I'm not an English native so I apologize if something seems wrong.

Thank you!





How to find class parameter datatype at runtime in scala

import scala.reflect.runtime.universe
import scala.reflect.runtime.universe._

def getType[T: TypeTag](obj: T) = typeOf[T]

case class Thing(
  val id: Int,
  var name: String
)
val thing = Thing(1, "Apple")

val dataType = getType(thing).decl(TermName("id")).asTerm.typeSignature

dataType match {
 case t if t =:= typeOf[Int] => println("I am Int")
 case t if t =:= typeOf[String] => println("String, Do some stuff")
 case _ => println("Absurd")
}

Not able to digest why result is Absurd instead of I am int?

My aim is to know data-type of class parameter at runtime and match it to predefined types.





Getting *NoSuchMethodException* when method defiantly is part of the class

I have the following class:

   class CountryDataItem (id: Long?, private val countryName :String?, private var countryFlagUrl : String?,
 var gameCount : Int,  var liveCount:Int)
    : BaseDataItem(id) {

    companion object {

        fun onCreateViewHolder(
            parent: ViewGroup,
            onRecyclerItemClickListener: OnRecyclerItemClickListener?
        ): RecyclerView.ViewHolder {
            val view: View =
                LayoutInflater.from(parent.context).inflate(R.layout.country_item, parent, false);
        }
    }
}

But when running:

  someKClass.java.getMethod("onCreateViewHolder",parent.javaClass,
                                onRecyclerItemClickListenerRef.get()?.javaClass)

I'm getting the exception. Can't understand why Maybe the reason related to the fact the the method is "static" but in java getMethod returned also static methods





Linq Reflection Expression throws exception on property of proprety

I'm trying to make functions with Linq Expressions arguments and am stuck on a problem.

Here's my test function:

public static void OutputField(Person p, Expression<Func<Person, string>> outExpr)
{
    var expr = (MemberExpression)outExpr.Body;
    var prop = (PropertyInfo)expr.Member;
    string v = prop.GetValue(p, null).ToString();
    Console.WriteLine($"value={v}");
}

If I define a Person object as

public class Person
{
    public PersonName Name { get; set; }
    public string City { get; set; }
}

public class PersonName
{
    public string First { get; set; }
    public string Last { get; set; }
}

and try to use it this way

Person person = new Person
{
    Name = new PersonName { First = "John", Last = "Doe" },
    City = "New York City"
};

OutputField(person, m => m.City);
OutputField(person, m => m.Name.First);

The output of the property City works, but the output of the property First of the property Name throws a System.Reflection.TargetException: 'Object does not match target type.' error. How do I make my test function work?





c# Reflection, how to get generic type class properties

I have a Generic type List<Shift> where

public class Shift
{
    [DisplayFormat(DataFormatString = "dd-MMM-yyy '(hours)'")]
    public DateTimeOffset Date { get; set; }

    [DisplayFormat(DataFormatString = "hh':'mm")]
    public TimeSpan TimeWorked { get; set; }
}

I'm trying to get schedule props with attributes using reflection

var props = typeof(List<ShiftDayItem>).GetProperties();
var ShiftProperty = props.Last();

But ShiftProperty contains no attributes, so I can't access Date or TimeWorked. Is reflection not aware of these or is there another way for me to get those properties? Thanks!





samedi 28 novembre 2020

Change return value of an instance method [closed]

I would like to adjust the return value of a method from an instance class and I am not quite sure if it is possible with or without Reflection. I could not figure it out and so I wanted to ask it here. Lets say I have for example the following class Foo:

public final class Foo {
    
    public final String getName() {
        return "Foo";
    }
    
}

Some context:

  • Foo class is from an external library
  • Foo class is not adjustable
  • Foo class is not extendable

So with this basic example I would like to get Bar returned from the method getName() instead of Foo. To be very explicit:

Foo foo = new Foo();
String name = foo.getName();
System.out.println(name) //prints "Bar"

Why do I need this?

Well I need to pass this instance of Foo to another method which only accepts an object of the type Foo. This method will call the method getName() and will do some additional calculation.

Actual use case:

I will try to give more context, hopefully it will be a bit more clear. There is a method within a builder class which is accepting an instance of KeyManagerFactory a method called setKeyManagerFactory(KeyManagerFactory keyManagerFactory). This builder class will internally call getKeyManagers on the KeyManagerFactory and it will return KeyManagers[]

The KeyManagerFactory is a final class, it doesn't have a public constructor at all. The getKeyManager method is also final. I already have a KeyManager[] and so I want to hack this KeyManagerFactory to return my own array own KeyManagers instead and supply it to the builder.





How to reselove ambiguity when when using reflection?

I'm trying to perform the following line in Kotlin:

var str: KFunction<String> = "some Word"::toUpperCase

But compiler says:

Overload resolution ambiguity. All these functions match. public inline fun String.toUpperCase(): String defined in kotlin.text public inline fun String.toUpperCase(locale: Locale): String defined in kotlin.text

I thought that writing KFunction should overcome the ambiguity since not writing nothing before the String in KFunction means that the KFunciton shouldn't get parameters and only return a String (which compatible with the function that is defined in kotlin.text package, but it seems that the compiler want some more info. I'm also trying the following assignment:

    var str: KFunction<java.util.Locale,String> = "some Word"::toUpperCase

And getting additional error saying that:

One type argument expected for interface KFunction

What Am I missing here?





vendredi 27 novembre 2020

c# Instantiate a class from its name

I'm trying to instantiate a class from a string (well an Enum really) containing it's name. I cant'f find a way to load the class type from the assembly. What is driving me mad is that type is in the same namespace and inside the same class, infact I resort using

System.Reflection.Assembly.GetExecutingAssembly().GetType(NamespaceAndClassName, true, true);

To be sure that the assembly is correct, but the same I receive "Could not load type [...] from assembly [...]" error. Name of the class is exact, if use debugger and copy the name of the class and then try to instantiate it elsewhere in the page using that exact name it works without problems.

The only thing that I guess may cause problem is that the type is a nested class, so I need some insight on this.

The structure of the page is this:

Namespace [...]
Public CLass OuterClass
   Static Method (that instantiate MyReflectionClass and calls MyReflectionMethod(nameOfTheClass))

   Public Class InnerClass (that I'm trying to instantiate with is name in string)

   Private MyReflectionClass
      Public MyReflectionMethod(string nameOfTheClass)
          var nameOfTheClass = typeof(Alerts).Namespace + ".Alerts." + localAlertType.ToString(); (this gives the full name of the class with NAMESPACE.OUTERCLASS.INNERCLASS and it's correct)
          System.Reflection.Assembly.GetExecutingAssembly().GetType(NamespaceAndClassName, true, true);

Sadly doesn't find the type





Jython: getDeclaredMethod double type parameter error java.lang.NoSuchMethodException

I'm working with Jython. I'm trying to call a method inside a Java class using getDeclaredMethod.

My problem is that the method I want to call has one parameter of type double and this type does not exist in Jython. So, if I call the method with java.lang.Double type, it throws me the error java.lang.NoSuchMethodException, because Double is different than double.

For example, my method is the following:

public void calculateDate(double value, Date startdate)

And I'm trying to use the following code to call the method:

classesParameters = [Double, Date]
calculateDateMethod = javaobject.getClass().getDeclaredMethod("calculateDate", classesParameters)
calculateDateMethod.setAccessible(True)
    
objects = [24.33, startDate]
dateCalculation = calculateDateMethod.invoke(javaobject, objects)

How can I get around this?

BR





Check if a object is serializable or can throw Serialization not supported Exception in .Net Core

I am trying to migrate WPF application to .NET core . In my project serialization is used heavily. Below function work well on .NET 4.7 framework but after migrating to .NET core 3.1 gives error ' Serializing delegates is not supported on this platform' .

public static T Clone<T>(T source)
    {
        if (ReferenceEquals(source, null))
            return default(T);

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            // test 
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T) formatter.Deserialize(stream);
        }
    }

I have changed serializable classes where ever => operator used or any property used delegates. After doing this part of code worked but some of module in project still throwing error - Serializing delegates is not supported on this platform.

Is there anyway to find which particular object or property is throwing this exception?

any hint or help appreciated. thanks.





Python — Init class reflectively

I am creating a commands system in Python. I have module vkcommands that has a class that processes commands from chat (this is a chat-bot), and inside it, I also have class VKCommand with attributes like name, usage, min_rank, etc. Then I have module vkcmds with submodules that implement these commands:

...
vkcommands.py
vkcmds
    |- __init__.py  # empty
    |- add_group.py
    |- another_cmd.py
    |- ...

Implementations of commands (e.g. add_group) look like this:

import ranks
import vkcommands
from vkcommands import VKCommand


class AddGroup(VKCommand):
    def __init__(self, kristy):
        VKCommand.__init__(self, kristy,
                           label='create',
                           # ... (other attributes)
                           min_rank=ranks.Rank.USER)

    def execute(self, chat, peer, sender, args=None, attachments=None):
        # implementation (called from vkcommands.py)

When a user sends a message in the chat, the command manager analyzes it and looks through the registered commands list to see if this is an ordinary message or a bot command. Currently I register all commands in the commands list manually like this:

class VKCommandsManager:
    def __init__(self, kristy):
        from vkcmds import (
            add_group,
            next_class
        )

        self.kristy = kristy
        self.commands = (
            add_group.AddGroup(kristy),
            next_class.NextClass(kristy)
        )

Now I would like all commands to be registered automatically using reflections instead. In Java, I'd iterate over all classes in my commands package, reflectively getConstructor of each, call it to retrieve the VKCommand object, and add it to the commands list.

How can I do so in Python? Again, what I need is to:

  1. iterate over all submodules in module (folder) vkcmds/;
  2. for each submodule, check if there is some class X that extends VKCommand inside;
  3. if (2) is true, then call the constructor of that class with one argument (it is guaranteed that the constructor for all commands only has one argument of a known type (my bot's main class));
  4. add the object (? extends VKCommand) constructed in (3) to the commands list that I can iterate over later.




jeudi 26 novembre 2020

Mark a whole assembly as dynamically accessed

With .NET 5, we can trim our project to reduce it's footprint. If we know that we will access a Type via reflection, we can mark it as dynamically accessed:

public void DoSomethingReflective<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>();

But is there also a way to mark a whole assembly as dynamically accessed?

public void DoSomethingReflective(Assembly assembly);




mercredi 25 novembre 2020

How to iterate over nested data classes using kotlin and refelction

I have a data class called report which is essentially a list of lists of variables - so nested data classes.

data class report(
    var list1 : List1,
    var list2 : List2
) : Parcelable

data class List1 (
    var a: Boolean = false,
    var b: Boolean = false,
) : Parcelable 


data class List2 (
    var c : Boolean = false,
    var d : Boolean = false,
) : Parcelable 

Using Kotlin and reflection I have a for loop which iterates over the top level data class and prints the name of the variable successfully. I'd like to iterate over each nested class and print the variables names but I can't figure out how to do that without explicitly referencing the nested class by name. The first for loop prints the correct data but the second for loop just prints "length".

        for (prop in report::class.memberProperties) {
            Log.d("DATACLASS", "${prop.name}")
            for (subProp in prop::class.memberProperties){
                Log.d("DATACLASS", "${subProp.name}")
            }
        }

In the second loop I feel like "prop" is not being expanded properly as a reference to the nested class. I tried something like "report.prop.name" or "report.${prop.name})" without success. I also tried assigning report.prop.name to a separate variable. Is this a simple syntax issue I'm missing? I did read other similar questions on Stack but didn't find a solution. Is it something to do perhaps with not having a class instance created at the right moment?





Custom annotation validator in Sring

I am currently creating a rest app using Spring and React. I've created a custom validator, that checks if data provided by DTO are correct. That's why I've also implemented some custom annotations to be checked by the validator.

I would like to ask if it is a good idea to create an annotation, for instance, @Discipline, that provides sport discipline is included in a set of disciplines available in the database. This kind of approach involves invoking the method of DisicplineService in Validator instead of DisciplineController.

Is it a good idea? Should I perform this kind of validation only in the controller?

Thanks for all answers and feedback.





Invoking beans in java using alias/real names as input from a flat file/map

I need to invoke and instantiate n number of bean classes and their variables based on the input from a flat file or map.

I tried below using reflection but this helps only instantiating String type of variables and not generic. Please suggest. Can I use any existing API or something else to deal with this case study ?

public class PersonInstantiator {

  public static void main(String[] args) throws Exception{
    HashMap<String, String> objHashMap = new HashMap<String, String>();
    objHashMap.put("KEY1", "KEY1 VALUE");
    objHashMap.put("KEY2", "KEY2 VALUE");

    Object object = null;
    Class<?> objClass = null;

    Properties properties = new Properties();
    properties.load(PersonInstantiator.class.getResourceAsStream("MappingFile.txt"));

    for (Map.Entry<String, String> entry : objHashMap.entrySet()) {
        String input[] = properties.getProperty(entry.getKey()).split("-");
        String className = input[0];
        String methodName = input[1];

        objClass = Class.forName(className);
        if (null == object) {
            object = objClass.newInstance();
        }
        Class<?>[] cArg = new Class[1];
        cArg[0] = String.class;
        Method method = objClass.getDeclaredMethod("set" + methodName, cArg);
        method.setAccessible(true);
        method.invoke(object, entry.getValue());

    }

    System.out.println(object);
   }

Class person looks like below:

public class Person {

private String name;

private String city;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getCity() {
    return city;
}
public void setCity(String city) {
    this.city = city;
}
@Override
public String toString() {
    return "Person [name=" + name + ", city=" + city + "]";
}

 }

Mapping file used is having below text.

 KEY1 = Person-Name
 KEY2 = Person-City




mardi 24 novembre 2020

Searching for a more elegant way to turn a MethodInfo to a Func through Expressions

I have the following code:

       public static Func<object[], object> CreateStaticFunc(this MethodInfo methodInfo)
    {
        var types = methodInfo.GetParameters().Select(p => p.ParameterType);



        if (methodInfo.ReturnType.Equals((typeof(void))))
        {
            Debug.LogError("Cannot create a Func from a method without a return type!");
            return null;
        }

        if (!methodInfo.IsStatic)
        {
            Debug.LogError("Cannot create a static Func from a non-static function!");
            return null;
        }

        var funcParams = methodInfo.GetParameters();

        var input = Expression.Parameter(typeof(object[]), "input");

        Func<object[], object> returned = null;

        //TODO research how to make this cleaner.
        switch (funcParams.Length)
        {
            case 0:
                returned = Expression.Lambda<Func<object[], object>>(Expression.Call(methodInfo), input).Compile();
                break;
            case 1:
                returned = Expression.Lambda<Func<object[], object>>(Expression.Call(methodInfo, 
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(0)), funcParams[0].ParameterType)), input).Compile();
                break;
            case 2:
                returned = Expression.Lambda<Func<object[], object>>(Expression.Call(methodInfo,
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(0)), funcParams[0].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(1)), funcParams[1].ParameterType)), input).Compile();
                break;
            case 3:
                returned = Expression.Lambda<Func<object[], object>>(Expression.Call(methodInfo,
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(0)), funcParams[0].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(1)), funcParams[1].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(2)), funcParams[2].ParameterType)), input).Compile();
                break;
            case 4:
                returned = Expression.Lambda<Func<object[], object>>(Expression.Call(methodInfo,
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(0)), funcParams[0].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(1)), funcParams[1].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(2)), funcParams[2].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(3)), funcParams[3].ParameterType)), input).Compile();
                break;
            case 5:
                returned = Expression.Lambda<Func<object[], object>>(Expression.Call(methodInfo,
                   Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(0)), funcParams[0].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(1)), funcParams[1].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(2)), funcParams[2].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(3)), funcParams[3].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(4)), funcParams[4].ParameterType)), input).Compile();
                break;
            case 6:
                returned = Expression.Lambda<Func<object[], object>>(Expression.Call(methodInfo,
                   Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(0)), funcParams[0].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(1)), funcParams[1].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(2)), funcParams[2].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(3)), funcParams[3].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(4)), funcParams[4].ParameterType),
                    Expression.Convert(Expression.ArrayAccess(input, Expression.Constant(5)), funcParams[5].ParameterType)), input).Compile();
                break;
        }
       

        return returned;
    }

}

This turns the MethodInfo into a Func/delegate so that it may be cached to improve performance since MethodInfo.Invoke is not very performant.

The code seems to work, but I cannot write a more elegant/concise way of doing this since I do not know the number of parameters ahead of time.

Can anyone help with this? Is it even possible?





How can I resolve this situation with Java Generics?

I have the following class hierarchy:

public abstract class MyParentObject {}
public abstract class MyObject<T> extends MyParentObject {}

public abstract class MyParentContainer<T extends MyParentObject> {
    private Class<T> valueType;
    protected MyParentContainer(Class<T> valueType) {
        this.valueType = valueType;
    }
}
public abstract class MyObjectContainer<T extends MyObject<?>> extends MyParentContainer<T> {
    protected MyObjectContainer(Class<T> valueType) {
        super(valueType);
    }
}

This works fine so far. There are several subclasses of MyObject and several container classes having some of those subclasses as valueType, e.g.

public class IntObject extends MyObject<Integer> {}
public class IntContainer extends MyObjectContainer<IntObject> {
    public IntContainer() {
        super(IntObject.class);
    }
}

Now I need to implement a container though that works with a mixed set of subclasses of MyObject.

public class AllObjectContainer extends MyObjectContainer<MyObject<?>> {
    public AllObjectContainer() {
        super(MyObject.class); // compile error here
    }
}

This does not compile, because "The constructor MyObjectContainer<MyObject>(Class) is undefined". Casting `MyObject.class` to `Class>` is not possible.

To solve this, I could use raw types:

  1. Change public class AllObjectContainer extends MyObjectContainer<MyObject<?>> to public class AllObjectContainer extends MyObjectContainer<MyObject>

This has consequences though because of type erasure, so I do not like this solution.

Alternatively I could enable casting by

  1. Change protected MyObjectContainer(Class<T> valueType) { to protected MyObjectContainer(Class<? extends T> valueType) { (add ? extends)
  2. Change super(MyObject.class) to super((Class<? extends MyObject<?>>) MyObject.class)

This method works, but the cast is marked as unchecked and changing the MyMiddleContainer-Constructor has potential side effects on other classes that extend it.

Are there any better solutions?





How to create an object just using class name in java with spring validator?

Im making spring validation and would like to make an generic validation for three similar entities: StudentOrder, EmployeeOrder, TeacherOrder. All that have the same fields. But its a different entities. The idea is to create a one validator for three entities.

Now i have this working on only one entity EmployeeOrder:

@Service
public class EmployeeOrderValidator implements Validator {

    @Autowired
    private OrderService OrderService;

    Class <?> typeOfOrder;

    @Override
    public boolean supports(Class<?> aClass) {
        typeOfOrder=aClass;
        return aClass.isInstance(EmployeeOrder.class);
    }

 @Override
    public void validate(Object o, Errors errors) {

  EmployeeOrder tripOrder = ((EmployeeOrder) o);
//making constraints  

}

}

So i would like to have something like that for all three Entities:

@Service
    public class EmployeeOrderValidator implements Validator {
    
        @Autowired
        private OrderService OrderService;
    
        Class <?> typeOfOrder;
    
        @Override
        public boolean supports(Class<?> aClass) {
            typeOfOrder=aClass;
            return aClass.isInstance(EmployeeOrder.class);
        }
    @Override
            public void validate(Object o, Errors errors) {
        //EmployeeOrder,StudentOrder or TeacherOrder will create
    
          typeOfOrder order = ((typeOfOrder) o);
    
        //making constraints  
        
        }
    

To create an object depends on giving type of aClass will create an instance with cast of this type.





lundi 23 novembre 2020

For ... in not yielding methods

Given the following:

export class MyClass {
    public dataA = 0
    private dataB = 123
    public myMethod(): any {
        return {
            test: 'true'
        }
    }

    constructor() {
        for (const propOrMethod in this) {
            console.log({propOrMethod})
        }
    }
}

const myInst = new MyClass()

I run this with ts-node index.ts and all i get is:

{ propOrMethod: 'dataA' }
{ propOrMethod: 'dataB' }

With no reference to myMethod. I would like to iterate over all the methods of my class, but they don't appear to exist





Generic method for converting QueryString to POCO class

I am trying to write a generic class to cast query string passed into a blazor page into a plain c# class. I want to reuse this, rather than specifying specific querystring parameters on every page declaration.

So far I am using reflection and generics but I'm getting an error when trying to pass the property type to the underlying extension methods;

Generic conversion class;

        public static TSearchParams GetSearchParamsFromQueryString<TSearchParams>(this Uri uri) where TSearchParams : SearchParams, new()
        {
            var searchParams = new TSearchParams();

            foreach (PropertyInfo prop in searchParams.GetType().GetProperties())
            {
                var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                if (type == typeof(Enum) || type.IsEnum)
                {
                    prop.SetValue(searchParams, uri.GetEnumFromQueryString<prop.PropertyType> (prop.Name));
                } 
                else
                {
                    prop.SetValue(searchParams, uri.GetValueFromQueryString<prop.PropertyType>(prop.Name);
                }
            }

This is failing when I try to use prop.PropertyType in uri.GetEnumFromQueryString<prop.PropertyType> (prop.Name)); for both get values and get enum.

Other relevent code;

POCO class

public class MySearchParameters: SearchParams 
{
        public MyEnumType? MyEnum { get; set; }
        public DateTime? DateStart { get; set; }
        public long? BranchId { get; set; }
        ///.. other types removed for brevity
}

To extract a specific value from a URI (this works in isolation);

        public static T GetValueFromQueryString<T>(this Uri uri, string key)
        {
            if (QueryHelpers.ParseQuery(uri.Query).TryGetValue(key, out var valueFromQueryString))
            {
                if (typeof(T) == typeof(int?) && int.TryParse(valueFromQueryString, out var valueAsInt))
                {
                    return (T)(object)valueAsInt;
                }

                if (typeof(T) == typeof(long?) && long.TryParse(valueFromQueryString, out var valueAsLong))
                {
                    return (T)(object)valueAsLong;
                }
                ///.. other types removed for brevity

                // otherwise get a string
                return (T)(object)valueFromQueryString.ToString();
            }

            return default(T);
        }

To extract an enum from a URI (this works in isolation);

        public static Nullable<TEnum> GetEnumFromQueryString<TEnum>(this Uri uri, string key) where TEnum : struct
        {
            if (QueryHelpers.ParseQuery(uri.Query).TryGetValue(key, out var valueFromQueryString))
            {
                TEnum res = (TEnum)Enum.Parse(typeof(TEnum), valueFromQueryString);
                if (!Enum.IsDefined(typeof(TEnum), res)) return null;
                return res;
            }
            return null;
        }

What is the correct way to cast the types during relfection? Or, is there a simpler way to convert all QueryString parameters to a C# class?





Unmarshal a struct out of data and use what's left over

I am looking to use the fields that are left over from what doesn't fit from unmarshaling the struct.

type Data struct {
     ID    string   `json:"id"`
     Name  string.  `json:"name"`
}

The data coming in sometimes matches the struct,

{
  "id": "ABC-123"
  "name": "Foo"
}

and sometimes it has extra key value pairs, with unknown keys or number of extra keys.

{
  "id": "ABC-1234"
  "name": "Bar"
  "color": yellow
  "shape": "oval"
  ...
}

I am interested in obtaining the diff from the two:

{
  "color": yellow
  "shape": "oval"
  ...
}

Using a custom UnMarshaller seems ideal, but I am running into issues with 'removing' a struct from the incoming response data.

dataStruct := make([]*Data, 0)

err := CustomUnmarshal(response.Body, &dataStruct)




dimanche 22 novembre 2020

Can I set a programmatically set a property of any type?

I'm trying to write a function that sets a property in a data class given a property type and a value. The data class has properties of several types, like String, View and Int, and some properties are nullable. I can make this work if I limit the functionality to one type, like this:

fun setDataValue(index: TableIndex, key: KMutableProperty1<CellData, String>, value: String) {
    val cellData = this.tableData[index]
    key.set(cellData, value)
}

setDataValue(0, CellData::name, "arlomedia")

But I can't find a way to allow multiple types, like this:

fun setDataValue(index: TableIndex, key: KMutableProperty1<CellData, Any?>, value: Any?) {
    val cellData = this.tableData[index]
    key.set(cellData, value)
}

setDataValue(0, CellData::name, "arlomedia")
setDataValue(0, CellData::status, null)
setDataValue(0, CellData::active, true)

In that case, the first function call shows the error, Type mismatch. Required: KMutableProperty1<CellData, Any?>, Found: KMutableProperty1<CellData, String>. I didn't expect that because Any? is a less specific type than String, so I figured I could supply a String when all that is required is Any?.

I also tried:

fun setDataValue(index: TableIndex, key: KMutableProperty1<CellData, *>, value: Any?) {
    val cellData = this.tableData[index]
    key.set(cellData, value)
}

setDataValue(0, CellData::name, "arlomedia")

In that case, the error on the function call goes away, but an error appears on the key.set line: Type mismatch. Required: Nothing, Found: Any?.

I suppose I could make a separate function for each data type and call the various functions as needed, but the purpose of this function is to abstract some more complex data access, and the benefit would be lost somewhat if I had to repeat that across multiple functions.

Is there a way to do this? I've been through the Kotlin Reflection documentation several times, plus this document (which for some reason I've only found in the "Migrating from Python" section), and many StackOverflow answers, but I haven't found anything that ties all the necessary pieces together.





Convert an Object to a user defined type class object without Reflection in C#

I have the following code where i am adding some class objects in an Array.

  Object[] ArrayOfObjects = new Object[] {typeof(Person), typeof(Company)};

Now if i want to iterate through my class items, how can i convert each item back to its original Type (such as Person and Company)? This might be possible using Reflection but i want to find out if C# has some built in functionality to achieve this.

  foreach (var item in ArrayOfObjects)
  {
     // TODO Convert item back to Original Type (Person or Company)
     // I am doing something like this but not working
     var person  =  Convert.ChangeType(item, typeof(Person));

     //I can not do this too as hardcoding the type inside the loop makes no sense
     var person = item as Person; //I need to convert item as Person or Company so that i can automate the tasks here.
  }

Much Thanks in advance.





Run Macro to generate code from parent class in Scala

I have a macro that I use to generate some code to call methods dynamically. The macro is more complex than this, but for simplicity let's say it works something like this

def myMacro[T]: Seq[MethodName]

so than when called on

class Hello {
  def one(a: Int, b: UserId): String = a.toString + b.id

  def two(c: Option[Int]): String = ""

  def three(d: Seq[Int], f: Set[Int]): String = ""
}
println(myMacro[Hello]) // Seq("one", "two", "three")

I need this macro to generate code for an internal framework we use at Candu, but I need to be able to call it from the parent's class. So what I want to achieve is:

trait Superclass {
  def aFakeMethod: String = ""

  val methods = myMacro[Self] // FIXME! self is not defined here...
}

class Hello extends Superclass {
  def one(a: Int, b: UserId): String = a.toString + b.id

  def two(c: Option[Int]): String = ""

  def three(d: Seq[Int], f: Set[Int]): String = ""
}
val hi = new Hello
println(hi.methods) // Seq("one", "two", "three")

Because the high number of classes in the framework, modifying the api between Hello and Superclass is very expansive. So I would need a way to do this without changing code in Hello

Any suggestions on how this could be achieved?





How to properly add a event-handler to a event-handler list of a control in .NET

I'm trying to write a class whose constructor expects a reference to a control / component, and the name of an event within the control class. The purpose is to dynamically subscribe to the specified event from the instance of the referenced control by adding a event-handler at runtime:

Public NotInheritable Class ExampleType(Of T As Component)

    Public ReadOnly Property Target As T

    Public Sub New(target As T, eventName As String)
        Me.Target = target

        Dim eventsProperty As PropertyInfo = 
            GetType(Component).GetProperty("Events", 
                                           BindingFlags.DeclaredOnly Or 
                                           BindingFlags.ExactBinding Or 
                                           BindingFlags.Instance Or 
                                           BindingFlags.NonPublic, 
                                           DefaultBinder, 
                                           GetType(EventHandlerList), 
                                           EmptyTypes, Nothing)
      
        Dim eventHandlerList As EventHandlerList = 
            DirectCast(eventsProperty.GetValue(target, BindingFlags.Default, 
                                               DefaultBinder, Nothing, 
                                               CultureInfo.InvariantCulture), 
                                               EventHandlerList)

        Dim eventHandler As New EventHandler(AddressOf Me.Target_Handler)
        eventHandlerList.AddHandler(eventName, eventHandler)
    End Sub

    Private Sub Target_Handler(sender As Object, e As EventArgs)
        Console.WriteLine("Test")
    End Sub

End Class

Example usage:

Dim target As NumericUpDown = Me.NumericUpDown1
Dim eventName As String = NameOf(NumericUpDown.ValueChanged)

Dim example As New ExampleType(Of NumericUpDown)(target, eventName)

The problem is that in the example above the Target_Handler method is never reached when in this case the Me.NumericUpDown1.ValueChanged event is raised, unless I invoke the event-handler method from code (with: eventHandlerList(eventName).DynamicInvoke(target, Nothing))

What I'm doing wrong?, how to solve my problem?. Thanks in advance.





Mod java application in using C++

The context

I am writing an application in Java which is moddable. The application searches a /mods directory for .jar files and uses org.reflections to find @Mod annotations on classes. It then creates a newInstance() of the class, and injects the mod's objects into the application's registries. The objects that are being injected into the application registries are primarily java.util.Supplier<T>s, where T is a complex object, such as a Tile.

That all works fine when writing the mod in Java.

  • Is it theoretically possible to achieve the same 'reflection & injection' effect with C++? If I wanted to make a mod for my application in C++ (as an example), is that theoretically possible?

Some approaches I have thought of

    1. I assume that the approach would have to be different...: org.reflections works off of ClassLoaders, so the C++ code would have to be in a format which could be loaded as such, if this were to work. It seems like inter-language conversion is often problematic (Converting Borland C++ code to Java code), so using an automated tool might be hard.
    1. Perhaps a different approach would be to not convert have either the modder, or the application convert the C++ code to Java, but to use a take on the JNI to load the C++ code as a library? Java can call methods from .dlls using the native keyword, assuming that it knows the name of the method it will call, and the library is loaded. If C++ can be compiled into a .dll, then would that help? How to compile a cpp to a dll in visual studio 2010 express
    1. Although I don't know a lot about it, perhaps a tool like SWIG would work for making the files cross compatible?

Would any of these three be viable solutions?

Any additional information or clarification, please ask.





vendredi 20 novembre 2020

python 3.x: Call function with shadowed global variable

I am building a non-intrusive alternative to pytest for running tests as part of a codebase that is in production. I would like to call each test with its own custom 'print' function instance so that I can collect the test use of print for each test individually without modifying the global print function or alter the streams for the rest of the production system.

My goal would be to pass a local to the function without needing the end user to modify the signature of the function to receive a fixture named 'print' as an argument to the test function.

Example:


def test_func(fixture_a):
  print("hello!") # this is not the default print function, and no global was created in the file either

I wasn't able to find a way in the inspect module to call a function with a dict to override its locals. Is this something that is possible in python 3.x?





Could not load file or Assembly `System.Windows.Forms , Version=4.0.0.0` cannot find the file

I am using reflection to search through assemblies that contain a certain interface, the one i am trying to find is a windows form that implements that interface, however the error i am getting claiming it cannot load the file, could it be down to not using reflection correctly or loading in the file properly.

string[] files = Directory.GetFiles(Environment.CurrentDirectory, "*.dll");

            foreach (string file in files)
            {
                try
                {
                    Assembly da = Assembly.LoadFrom(file);

                    foreach (Type type in da.GetTypes())
                    {
                        debugger = (IDebugger)Activator.CreateInstance(type.GetInterfaces().First(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDebugger)));
                        break;
                    }
                    break;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    continue;
                }
            }

            if (!(debugger == null))
                debugger.VirtualMachine = this;

Error

System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeModule.GetTypes()
   at System.Reflection.Assembly.GetTypes()
   at SVM.SvmVirtualMachine..ctor() in C:\Users\Ollie\Desktop\Work\SimpleVM\SVM\VirtualMachine\VirtualMachine\SvmVirtualMachine.cs:line 49
System.IO.FileNotFoundException: Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified.
File name: 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'




How can I dynamically build an Enum select with Blazor?

I'm trying to build a Generic form component with Blazor. Currently, all other input types are working except for enums selects. I think this happens because the compiler doesn't know the specific enum type when trying to add the expression and callback functions:

public partial class GenericForm<ViewModel> : ComponentBase where ViewModel : new()
{
    [Parameter]
    public ViewModel Model { get; set; }
    public readonly PropertyInfo[] Properties = typeof(ViewModel).GetProperties();
    [Parameter] public EventCallback<ViewModel> OnValidSubmit { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (Model == null)
        {
            Model = new ViewModel();
        }
        await base.OnInitializedAsync();
    }
    public RenderFragment CreateComponent(PropertyInfo property) => builder =>
    {
        var typeCode = Type.GetTypeCode(property.PropertyType);
        if (property.PropertyType.IsEnum)
        {
            BuildEnumComponent(builder,property);
        }
        else
        {
            switch (typeCode)
            {
                case TypeCode.Int32:
                    BuildComponent<double>(property, builder, typeof(InputNumber<double>));
                    break;
                case TypeCode.Int64:
                    BuildComponent<long>(property, builder, typeof(InputNumber<long>));
                    break;
                case TypeCode.Int16:
                    BuildComponent<int>(property, builder, typeof(InputNumber<int>));
                    break;
                case TypeCode.Decimal:
                    BuildComponent<decimal>(property, builder, typeof(InputNumber<decimal>));
                    break;
                case TypeCode.String:
                    BuildComponent<string>(property, builder, typeof(InputText));
                    break;
                case TypeCode.Boolean:
                    BuildComponent<bool>(property, builder, typeof(InputCheckbox));
                    break;
                case TypeCode.DateTime:
                    BuildComponent<DateTime>(property, builder, typeof(InputDate<DateTime>));
                    break;
                default:
                    Console.WriteLine("Unknown property type");
                    break;
            }
        }
        
    };

    private void BuildEnumComponent(RenderTreeBuilder builder,PropertyInfo property)
    {
        Guid id = Guid.NewGuid();
        builder.AddMarkupContent(1, $"<label for=\"{id}\">{property.Name}</label>");
        builder.OpenElement(2, "select");
        builder.AddAttribute(3, "id", id.ToString());
        builder.AddAttribute(4, "Value", Enum.GetValues(property.PropertyType).GetValue(0));
        builder.AddAttribute(5, "ValueChanged", CreateCallback<Enum>(property));
        builder.AddAttribute(6, "ValueExpression", CreateExpression<Enum>(property));

        foreach (var value in Enum.GetValues(property.PropertyType))
        {
            builder.OpenElement(1, "option");
            builder.AddAttribute(2, "value", value.ToString());
            builder.CloseElement();
        }
        builder.CloseElement();
    }


    private void BuildComponent<PropertyType>(PropertyInfo property, RenderTreeBuilder builder, Type inputType)
    {
        var propertyValue = property.GetValue(Model);
        var id = Guid.NewGuid();
        builder.AddMarkupContent(0, $"<label for=\"{id}\">{property.Name}</label>");
        builder.OpenComponent(1, inputType);
        builder.AddAttribute(2, "id", id.ToString());
        builder.AddAttribute(3, "Value", propertyValue);
        builder.AddAttribute(5, "ValueChanged", CreateCallback<PropertyType>(property));
        builder.AddAttribute(6, "ValueExpression", CreateExpression<PropertyType>(property));
        builder.CloseComponent();
    }

    private EventCallback<PropertyType> CreateCallback<PropertyType>(PropertyInfo property)
    {
        return RuntimeHelpers.TypeCheck(EventCallback.Factory.Create(this, EventCallback.Factory.CreateInferred(this, __value => property.SetValue(Model, __value), (PropertyType)property.GetValue(Model))));
    }
  

    private Expression<Func<PropertyType>> CreateExpression<PropertyType>(PropertyInfo property)
    {
        var constant = Expression.Constant(Model, Model.GetType());
        var exp = Expression.Property(constant, property.Name);
        return Expression.Lambda<Func<PropertyType>>(exp);
    }

}

Its crashing in this line: return Expression.Lambda<Func<PropertyType>>(exp); with this error: System.ArgumentException: 'Expression of type 'Backender.Core.Common.Enums.EntityFieldType' cannot be used for return type 'System.Enum'' . EntityFieldType is also an enum. Any tips?





jeudi 19 novembre 2020

How to get Methods from KClass in Kotlin

In java when i have a Class<> instance, i have the getMethod that return a Method and it is very easy to use. As i can see Kotlin makes life harder because such a method doesn't exist. is there a nice way to get a specific method beside of turning the KClass to Class and then using it exactly as in Java?





How to get all enumerable properties of a specific type from a class

Lets say I have a poco class that looks like this:

public MyClass
{
    public IAssimilator p1 {get; set;}
    public IAssimilator p2 {get; set;}
    public IAssimilator p3 {get; set;}
    public string n1 {get; set;}

    public List<IAssimilator> p4 {get; set;}
    public IEnumerable<IAssimilator> p5 {get; set;}
    public List<int> n2 {get; set;}
}

I have a method elsewhere that returns a List of all properties on MyClass that have type of IAssimilator. It looks like this:

private List<IAssimilator> DeltaTrackedMembers()
{
    var myInstance = new MyClass;
    ....
    ...
    return typeof(MyClass).GetProperties()
                .Where(p => p.PropertyType == typeof(IAssimilator))
                .Select(p => p.GetValue(myInstance) as IAssimilator)
                .ToList();
}

It will return a List<IAssimilator> that contains the values of p1 thru p3.

What I would like to add is something to also get IAssimilator values inside any enumerable property. In this case, it should return a List that contains the values in p4 and p5, but not n2. I don't really know where to start.





Unity, get access to internal class of another packages

So, I got this official unity package called python for untiy. It has a few internal class and a few public classes.

I need to access a property of internal class. So basiclly what i did was, I find the container assembly using some public class in that package. So basicly:

var pythonPackageAssembly = typeof(ThePublicClass).Assembly;
var theInternalType = pythonAssembly.GetType("internalClassName");
if (type is null){
    Oah no, it is null
}

But it says the type I found is null. I wonder if there's any mistake I made during the process. Or what is the correct way to access it, thank you!

There is a few similiar topiced question in SO, here is a quick explanation why I'm in a bit different situation

  1. First Link, I don't have a instance of the class to start from, and I cannot modify the package.
  2. Second Link, I basically follow the answer there, but the problem is I dont think in unity C# you can give full trust




mercredi 18 novembre 2020

How to invoke base-class method of injected object?

(I couldn't come up with a succinct title for this question that didn't drag on.)

I have a base class that has one public method:

public class MyBaseClass
{
    public void MyBaseMethod()
    {
        // Here is where the functionality will go, that is described below.
    }
}

I have another class, derived from my base class, that contains injected objects that also derive from MyBaseClass:

public class MyWorkingClass : MyBaseClass
{
    // All of these objects also derive from MyBaseClass.
    private readonly IClassOne _classOne;
    private readonly IClassTwo _classTwo;
    private readonly IClassThree _classThree;

    public MyWorkingClass(
        IClassOne classOne,
        IClassTwo classTwo,
        IClassThree classThree)
    {
        _classOne = classOne;
        _classTwo = classTwo;
        _classThree = classThree;
    }

    public SomeMethod()
    {
        // Stuff goes here.

        // Call base method here.
        MyBaseMethod();
    }
}

What I want to happen is that the call to MyBaseMethod will collect all of the fields declared in the class. For each field, get its instance and call its own MyBaseMethod.

I can get all of the fields in a class instance:

var fields = GetType()
    .GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)
    .ToList();

For each field in the list, I can get its field type, instance and its own declared methods:

foreach (var field in fields)
{
    var fieldType = field.FieldType;

    var fieldInstance = field
        .GetValue(this);

    var methods = fieldType
        .GetMethods();
}

My problem is that my base-class method, MyBaseMethod, is not included in the list of methods. I have also tried GetRuntimeMethods(), but it is not included there either.

If I could get access to the base-class method, then I could invoke it:

var methodInfo = fieldType
    .GetMethod('MyBaseMethod');

methodInfo
    .Invoke(fieldInstance, null);

Question: How can I manage to invoke my base-class method in each field instance, given that its type is listed as being an interface?

Thanks.





Implicit resolution fail in reflection with ToolBox

I am trying to generate Avro4s's RecordFormat in reflection based on class path. The following code throws an error.

case class MyCaseClass(a: Int)
println(toolBox.compile {
  toolBox.parse(
    s"""
       |import com.sksamuel.avro4s._
       |import mypackage.MyCaseClass
       |RecordFormat[MyCaseClass]
       |""".stripMargin
  )
}())

could not find implicit value for evidence parameter of type com.sksamuel.avro4s.Decoder[mypackage.MyCaseClass]

RecordFormat is like

object RecordFormat {
   def apply[T <: Product : Encoder : Decoder : SchemaFor]: RecordFormat[T] = apply(AvroSchema[T])
}

I can see, it can resolve Encoder[MyCaseClass] and SchemaFor[MyCaseClass] but fails for Decoder[MyCaseClass].

The same code can resolve RecordFormat[MyCaseClass] without reflection.

I can see that Decoder is implemented with macro similar to Encoder.

implicit def applyMacro[T <: Product]: Decoder[T] = macro applyMacroImpl[T]

Why reflection cannot resolve the implicit evidence?





ArrayList

ArrayList<Integer> intList = new ArrayList<>();
intList.getClass().getDeclaredMethod("add", Integer.class); // throws NoSuchMethodException

//where as
intList.getClass().getDeclaredMethod("add", Object.class); // is just fine.

Of course in this case I want the first one to work. Or at least figure out how get a method from a generic type parameter.

When looping over the declared methods the add method does explicitly say Object:

public boolean java.util.ArrayList.add(java.lang.Object)

My guess is I am missing something simple.





Get values inside PropertyInfo object

I have this object propInfo (that is PropertyType) listed below that is of type ICollection and has an array of values in it.

How can I acess it's values and build a string with all of them (Strigbuilder for example)?

                var propName = m.Groups[1].Value;

                // returns ICollection
                var propInfo = baseType.GetProperty(propName);

                // Find if the prop is repetetive 
                if (typeof(IEnumerable).IsAssignableFrom(propInfo.PropertyType))
                {
                    // Get the value (multiple values inside) and create a string
                    

                }




mardi 17 novembre 2020

PropertyInfo.GetValue throws NullReferenceException

I want to create a Blazor DropDown component and I would use reflection in it. I give the data, the name of the text property and the name of the value property as parameters for it. Unfortunatelly when I get the value of the property it throws NullReferenceException after I get the value:

@foreach (TItem item in Data ?? Array.Empty<TItem>())
{
  PropertyInfo prop = typeof(TItem).GetProperty(ValueProperty);
  string text = prop.GetValue(item, null).ToString();
  ...
}

@code {
  [Parameter]
  public IEnumerable<TItem> Data { get; set; }
  [Parameter]
  public string ValueProperty { get; set; }
  [Parameter]
  public string TextProperty { get; set; }
}

TItem is:

public class DropDownData
{
  public int ValueInt { get; set; }
  public string ValueString { get; set; }
  public string Text { get; set; }
}

Thank you in advance.





How do I get a list of all properties including those within nested objects within a class file

I have a class with nested properties, similar to the following:

Class X { 
public ClassA propA {get;set;} 
public IEnumerable<ClassB> propB {get;set;}
}

where

Class A { 
    public IEnumberable<ClassC> prop C {get;set;} 
    public ClassD propD{get;set;} // Enum type
}

Class B { 
    public ClassE propE {get;set;} 
    public string prop1...prop10 {get;set;} 
    public IEnumerable<ClassF> propF{get;set;}
...} and so on

I am required to develop a generic method which can accept any Class File and list out all properties along with their values across all these layers. There can be files with a complexity as shared in this example or more!

I have used Reflection and LINQ queries to figure the names of these properties but can only get this information for upto 2 layers and have not been able to identify properties which could be of another class type and obtain it's corresponding properties as well. I would want to keep extensive looping/ recursion as the last approach but would rather prefer LINQ solutions as irrespective of the complexity, this would have to be processed in under a minute.

I seem to have exhausted all options and would love to hear your solutions to this.

Many Thanks!





How to assign primitive type value to a method args using Java reflection?

I'm new to java reflection concept. I need to access one method from a particular class using Java reflection. That method has three different types of argument like this,

public void print(int start, String middle, int end) {
   System.out.println(start);
   System.out.println(middle);
   System.out.println(end);
}

I tried to call that method like this,

...
method.invoke(null, "middle", null);
...

I got IllegalArgumentException. I know null is acceptable for wrapper type args, but I just tried this method for knowing how it is working.

So, my main question is, how to pass primitive type value to that method argument via reflection? also, how to pass default value for primitive type arg via reflection? (for eg: let's assume, I don't need end arg value during runtime, then how to pass 0 for end arg)

Is there any way to solve this issue?





Can some explain the reflection package API in *very* simple terms?

I'm having a hard time understanding the documentation/examples out there describing the reflection package. I'm an imperative-programming veteran but a Haskell newb. Can you walk me through a very simple introduction?

Package: https://hackage.haskell.org/package/reflection





How to prevent C++ symbols (reflection) in static library from being striped by Xcode when linking? (without using -force_load)

I am using C++ reflection in a static library to dynamically create classes. However when it's linking, lot of symbols are stripped because they are treated as dead symbols. The classes could not be created when the app is running.

I know that the link flag force_load could be used to load all the symbols in the static library. However this might cause other duplicated symbol problems, so force_load could not be used.

Here is what the reflection like:

// libA.a
// x.cpp
class X: public Y {
};
REGISTER_MACRO(X);
// the macro manages a name string to std::make_unique<Y> map, 
// the type in make_unique is the super class Y

Any suggestion for this? e.g., is there any link flags to prevent stripping single symbol?





lundi 16 novembre 2020

How to find and register dependencies using reflection

I want to do the following:

Imagine I have the classes that implement the interface IValidator. I want to find all of those classes and register them in dotnet core standard dependency injection container.

Example:

        services.AddSingleton<IValidator<Delete.Command>, Delete.CommandValidator>();
        services.AddSingleton<IValidator<CreateOrUpdate.Command>, CreateOrUpdate.CommandValidator>();

I know how to find the classes.

var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));

The problem is that I don't know how to register them after I find them.

I don't know what keywords to use to search in internet for information. That's why I decided to ask question here.

Thanks!





C# - Get FieldInfo value from static readonly members of static classes using reflection

I'm trying to make a system that using reflection and during compilation time, it's able to generate a configuration file for some classes. The usage of a configuration file is to avoid using reflection at runtime. Let me explain.

I have something like

public abstract class BaseClass
{
    public abstract string ID { get; }
}

and multiple implementations like

public class ClassOne : BaseClass
{
    public override string ID { get { return "Class1"; } }
}

public class ClassTwo : BaseClass
{
    public override string ID { get { return "Class2"; } }
}

public class ClassThree : BaseClass
{
    public override string ID { get { return "Class3"; } }
}

What I did in order to be able to use each implementations in their proper context in a static way, is to create for each context a static class like this:

namespace ContextOne
{
    internal static class Container
    {
        public static readonly ClassOne = new ClassOne();
    }
}

In this way, sharing the BaseClass with all the contexts, I can create multiple children that defines specific values for specific usages. In a context, i can define a .cs file like this:

namespace MyContext
{
    public class MyClass : BaseClass
    {
        public override string ID { get { return "MyClass"; } }
    }

    public class YourClass : BaseClass
    {
        public override string ID { get { return "YourClass"; } }
    }

    internal static class Container
    {
        public static readonly MyClass Option1 = new MyClass();
        public static readonly YourClass Option2 = new YourClass();
    }
}

I also made a static class in which the static constructor is using reflection to get all the members defined in all the Assemblies of the project so that it can keep an updated internal cache of all these classes associating to them a configuration that is saved on a text file. The cache is a dictionary in which I use the ID defined in each class as key and a ConfigClass as value. I disabled the execution of all the code that uses reflection at runtime. This is a very simplified version of this class:

public static class Manager
{
    private static readonly Dictionary<string, ConfigClass> _cache = new Dictionary<string, ConfigClass>();

    static Manager()
    {
        _cache = LoadFile();

        // get a collection of valid IDs defined in the project.
        List<string> validIDs = new List<string>();
        List<Type> containers = GetTypesWithNameInAllAssemblies(".Container", true);
        foreach(var cont in containers)
        {
            MemberInfo[] members = cont.GetMembers(BindingFlag.Static | BindingFlag.Public);
            foreach(var mb in members)
            {
                FieldInfo field = cont.GetField(mb.Name);
                if(field.FieldType.BaseType == typeof(BaseType)
                {

                    //********************* 
                    string id = /* TODO */;
                    //*********************

                    validIDs.Add(id);
                }
            }
        }

        // update the cache.
        AddMissingEntriesToCache(validIDs, _cache);
        RemoveObsoleteEntriesFromCache(validIDs, _cache);
        SaveFile(_cache);
    }

    private static List<Type> GetTypesWithNameInAllAssemblies(string name, bool fullNameEndsWith = false)
    {
        List<Type> wantedTypes = new List<Type>();
        Assembly[] assemblies = GetAssemblies();
        for (int i = 0; i < assemblies.Length; i++)
        {
            Type[] types = assemblies[i].GetTypes();
            for (int j = 0; j < types.Length; j++)
            {
                if (fullNameEndsWith)
                {
                    if (types[j].FullName.EndsWith(name))
                    {
                        wantedTypes.Add(types[j]);
                    }
                }
                else
                {
                    if (types[j].Name == name)
                    {
                        wantedTypes.Add(types[j]);
                    }
                }
            }
        }
        return wantedTypes;
    }
}

as you can see from the code, I'm not able to get the ID from the FieldInfo object I got with reflection. I tried using

string id = field.GetValue(null) as string;

but I'm obviously making a mistake: I probably need to get the static instance of the derived classes defined in the Container in order to do that, but I have no clue on how to do it. Possibly, once the instance is defined, it should stick to the static member so that I will not create other instances causing memory leaks or other sort of issues.

Thank you very much !! :)





dimanche 15 novembre 2020

How can I retrieve a class from a method reference in javascript?

I would like to do this:

function call(method) {
    const object = // Retrieve the class that declares the method and then construct an instance dynamically.
    method.call(object) // So 'this' is bound to the instance.
}

call(MyClass.prototype.myMethod)
call(AnOtherClass.prototype.anOtherMethod)

My goal is to create the instance from a dependency container. That's why the method has to be bound to an instance that will have all the dependencies required by the class.





Determine which properties in a class has a special attribute

I have a class with some property like this:

public List<Some1POCO> SomeProp1List{ set; get; }

[SomeAttribute]
public List<Some2POCO> SomeProp2List { set; get; }
.
.
.

I want to find out properties that has "SomeAttribute" and then include this properties in a EF query

how to use it as a condition in LINQ queries ?





samedi 14 novembre 2020

How to retrieve class property types from a class type?

I have the following class:

class Animal {
  name: string
  age: number
}

I want to be able to retrieve the types of the class's properties without it being initialized. Here is how I expect to be using this:

function getClassPropertyTypes(classType) {
  // perform some magic
}

// The returned value should be either an array or object with the property key and its type
getClassPropertyTypes(Animal)




vendredi 13 novembre 2020

Match a list of properties in a class with a list of strings

I have this object:

 public partial class Subjects
{
    public Guid SubjectId { get; set; }
    public string Code { get; set; }
    public Guid OrganizationId { get; set; }
    public string PreferredName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public string Gender { get; set; }
    public string LastNameInitial { get; set; }
    public string CodeDisplay { get; set; }
    public Guid? RaceId { get; set; }
    public Guid? MaritalStatusId { get; set; }
    public Guid? StatusId { get; set; }
    public string Rank { get; set; }
    public string Email { get; set; }
    public string MobilePhone { get; set; }
    public bool MobilePhoneDoNotLeaveMsg { get; set; }
    public bool MobilePhoneDoNotText { get; set; }
    public string WorkPhone { get; set; }
    public bool WorkPhoneDoNotLeaveMsg { get; set; }
}

And I have this list of strings that are names of the properties in the class that I need to encrypt:

public static List<string> EncryptedColumns = new List<string> { "SocialSecurityNumber", "CodeDisplay", "FirstName", "LastName", "MiddleName", "PreferredName", "LastNameInitial" };

Right now the way these two strings match is using reflection to check each item in the list to a property in the class. If there was a match, the value was encrypted. I want to avoid using reflection for this due to the overhead. Here is how the current program does this matching:

            foreach (string name in EncryptedColumns)
            {
                var property = encryptSubject.GetType().GetProperty(name);
                if (property != null)
                {
                    var value = property.GetValue(encryptSubject , null);
                    if (value != null)
                    {
                        string finalvalue = value.ToString();
                        
                        property.SetValue(encryptSubject, Encrypt(finalvalue), null);
                    }
                }
            }

This does work, but reflection carries a lot of overhead. Is there a better method for doing this?





How to determine if an enum has been defined as a bitmask flag?

How would someone detect if an enum has been defined as a bitmask flag, or a series of single case values?

Example:

public enum ElementalType
{
    Normal = 0,
    Fire = 1,
    Frost = 2,
    Energy = 3,
    Nature = 4,
    Sonic = 5,
    Arcane = 6,
    Shadow = 7,
    Holy = 8,
}

Would be detected as a normal single-case enum.

However:

    public enum CubeFaceVisibility
    {
        None = 0,
        /// <summary>
        /// NegativeZ
        /// </summary>
        North = 1,
        /// <summary>
        /// PostiveX
        /// </summary>
        East = 2,
        /// <summary>
        /// PostiveZ
        /// </summary>
        South = 4,
        /// <summary>
        /// NegativeX
        /// </summary>
        West = 8,
        /// <summary>
        /// PositiveY
        /// </summary>
        Top = 16,
        /// <summary>
        /// NegativeY
        /// </summary>
        Bottom = 32,
        NorthSouth = North | South,
        EastWest = East | West,
        TopBottom = Top | Bottom,
        NorthEastSouthWest = North | East | South | West,
        All = North | South | West | East | Top | Bottom
    }

Would be detected as a bitmask style enum.

Does anyone know how to write a function that can determine the culture of enums? I'm tagging this as reflection, but that may be irrelevant to the question.





Weird behavior with orthogonal procrustes

Given two matrices mat1 and mat2, each one representing a set of 3 points in a 3 dimensional space, I want to rotate mat2 so that it matches mat1 using orthogonal procrustes :

mat1 <- t(matrix(c(1.16, 0.21, 0.11, -0.78, -0.02, -0.73, -0.37, -0.18, 0.62), nrow=3))
mat2 <- t(matrix(c(0.40, -0.94, -0.05, -0.91, 0.24, -0.38, 0.51, 0.70, 0.43), nrow=3))

Q <- cds::orthprocr(mat1 , mat2)$Q
mat2_rotated <- mat2 %*% Q

The matrix Q should then represent the optimal rotation / reflection to apply to mat2 to fit as much as possible mat1. This also means that the optimal rotation/reflection between mat1 and mat2_rotated should be the identity matrix. However, this doesn't seem to be the case :

Q_2 <- cds::orthprocr(mat1 , mat2_rotated)$Q

#frobenius norm of the difference between Q_2 and Identity :
sqrt(sum((Q_2 - diag(3))^2)) # returns 2 !!!

Where am I wrong? Also what would be the way (some other implementation maybe?) to obtain Identity as optimal orthogonal matrix when the considered matrices are already fitted?

Note that, in the above example, I remark that mat2_rotated is invariant regarding Q_2 rotation / reflection :

sqrt(sum((mat2_rotated - (mat2_rotated %*% Q_2))^2)) # returns 1.400699e-15




Java Annotation Processing SuperClass Data extraction

Hi I am creating a code generation program, as part of it I need to extract info of the GenericType passed into a class which extends an Abstract class, for further clarification This is the class I annotated with my annotation

@MyAnnotation
public class First extends ParentC<Story, String> {
...
}

I was able to extract the element First from roundEnviornment now I need to know which classes that is provided to its super class( Story and String) I extracted super class using below snippet but I couldn't get any info on Generic type provided

            TypeElement elm = //extraction of this element was successful
            messager.printMessage(Diagnostic.Kind.NOTE,"==============="+ elm.asType().toString());
            TypeMirror parent = elm.getSuperclass();
            DeclaredType parentType = (DeclaredType)parent;
            Element parentEl = parentType.asElement();
            messager.printMessage(Diagnostic.Kind.NOTE,"==============="+ parentEl.asType().toString());
            messager.printMessage(Diagnostic.Kind.NOTE, "==============="+ parentEl.getSimpleName());

the output of the code is given below

Note: ===============com.demo.service.First
Note: ===============com.demo.ParentC<T,K>
Note: ===============ParentC

So is there any way I can get the Type of the generic type as Story class and String class ?





How to pass an object to a method using reflection in java

I am working on some code which takes a string input dynamically , so i chose reflection as i didnt find any other better approach for it ,

My current code:

Class xyzClass = Class.forName("com.example.Xyz");

Object abcObj =  abcService.generateAbcObj("some string input");
Method method = xyzClass.getDeclaredMethod("add", abcObj); // i want to pass this abcObj to this declared method add but getDeclaredMethod takes class as a parameter

Can anybody suggest way to do in reflection as i want it in a dynamic way or any other way to achieve it in a better sense ?





jeudi 12 novembre 2020

Model for a Class that desrcibes other Classess

I've got some problem that i can't figure out for a loong time.

I'm building web app in core-plugin architecture. Plugins provides some functionality by methods. For example:

public void doSomething(Input input){
    // Some functionality
}

The Input class can be basically anything. For example:

public class Input{
    private String text;
    private List<String> textList;
    private InnerField inner;
    private List<InnerField> innerList;
} 
public class InnerField{
    private String text;
    pirvate Integer number;
}

The core module is collecting all methods of plugins and provides them to webpage user so the user can pick a method and set input data.

I know how to use java reflection api and get into metadata of methods and classes. The problem is with figuring out the structure of Class that would describe the Input and in same time store the data of Object.

In other words. I want to create a Class let's say InputData that i can pass to frontend which will:

  • build form based on fields declaration
  • fill form based on data

This InputData on submit would be serialized to json and saved in DB and, of course, should be mapped to original Input class so we can pass it to the plugin method.

I was thinking about something like this:

public class InputField{
    private String className; //java.lang.String, some.package.CustomClass
    private boolean variable; // if true, the strVal is a reference to other object (stored in map)
    private String strVal; //value parsed to String if it's basic type like String, Integer, Boolean
    private List<InputField> fields; //list of inner fields if it's complex type
}

And this would be good enough but only if the Input class would not have List types in it.

The one last kicker is that each field (even Input object itself) can be a referece to some variable. So for example the user provided some values for Input class and want to reuse that so in form he just provides a name of the variable that it refers to. At the runtime when we invoke the plugin method the processor istead of parsing this json to data would search for data referenced by the variable name.

I know.. probably none of you know what i'm talking about but i'm in so awfull mindset that i can't even explain it well.

I am hoping that somone will kind of understand me and put me on the right tracks. Maybe someone had similar issue?





How get companion method reference (KFunction<>) by refelection

In Java it is possible to get a reference to static method in the following way (using reflection):

Method method = Class.forName("java.util.HashMap").getMethod("put", Object.class, Object.class);

In Kotlin it is possible to get a reference (type KFunctionX<>) to instance method in the following way (using reflection):

    var methodRef : KFunction0<Unit> = someInatance::instanceMethod

But when trying to get a companion method (using reflection) in the following way:

    var companionMethod = SomeJavaClass::someCompanionMethod

I'm getting an unresolved reference error





Avoid org.reflections.Reflections logs: given scan urls are empty. set urls in the configuration etc

When I run any unit test or my application I notice logs:

11:32:36.703 [main] WARN org.reflections.Reflections - given scan urls are empty. set urls in the configuration
11:32:36.731 [main] DEBUG org.reflections.Reflections - going to scan these urls:
file:/C:/Users/Pawel/Documents/s-dmw-pom/s-dmw/target/classes/
11:32:36.835 [main] INFO org.reflections.Reflections - Reflections took 102 ms to scan 1 urls, producing 5 keys and 110 values 
11:32:36.875 [main] WARN org.reflections.Reflections - given scan urls are empty. set urls in the configuration
11:32:36.883 [main] DEBUG org.reflections.Reflections - going to scan these urls:
file:/C:/Users/Pawel/Documents/s-dmw-pom/s-dmw/target/classes/
11:32:36.914 [main] INFO org.reflections.Reflections - Reflections took 31 ms to scan 1 urls, producing 5 keys and 61 values 
11:32:36.929 [main] WARN org.reflections.Reflections - given scan urls are empty. set urls in the configuration
11:32:36.929 [main] DEBUG org.reflections.Reflections - going to scan these urls:
file:/C:/Users/Pawel/Documents/s-dmw-pom/s-dmw/target/classes/
11:32:36.992 [main] INFO org.reflections.Reflections - Reflections took 63 ms to scan 1 urls, producing 7 keys and 149 values 
11:32:36.992 [main] DEBUG org.reflections.Reflections - expanded subtype java.lang.Comparable -> java.lang.Enum
11:32:36.992 [main] DEBUG org.reflections.Reflections - expanded subtype java.io.Serializable -> java.lang.Enum
...

I read that those logs are produced by java org.reflections.Reflections:

Reflections.scan()

protected void scan() {
  if (configuration.getUrls() == null || configuration.getUrls().isEmpty()) {
    if (log != null) log.warn("given scan urls are empty. set urls in the configuration");
    return;

    log.debug("going to scan these urls:\n{}", Joiner.on("\n").join(configuration.getUrls()));

  ExecutorService executorService = configuration.getExecutorService();
  List<Future<?>> futures = Lists.newArrayList();

  for (final URL url : configuration.getUrls()) {
    try {
      if (executorService != null) {

And they are invoked when setUrls(null):

Reflections reflections = new Reflections(new ConfigurationBuilder()
      .setUrls(...)));

How to avoid them?





mercredi 11 novembre 2020

How to reflect concrete return types for methods of classes defined at runtime using the Scala ToolBox?

When reflecting the foo() method of the class Cls we can easily get the concrete return type using the following.

class Cls {
  def foo() =
    List("A", "B")
}

val classType = ru.typeOf[Cls]
val classMirror = toolbox.mirror.reflectClass(classType.typeSymbol.asClass)
val ctorSymbol = classType.decl(ru.termNames.CONSTRUCTOR).asMethod
val methodSymb = classType.decl(ru.TermName("foo")).asMethod
val ctor = classMirror.reflectConstructor(ctorSymbol)
val instance = ctor()
val im = toolbox.mirror.reflect(instance)
val foo = im.reflectMethod(methodSymb)
println(foo())  // List(A, B)
println(methodSymb.returnType) // List[String]

However, if we define the class Cls at runtime via the toolbox and then use the same method reflection process, we will only get the abstract return type (List) of the foo() method.

import ru._

val tree =
  q"""class Cls {
        def foo() =
          List("A", "B")
    }""".asInstanceOf[ru.ClassDef]

val classSymbol = toolbox.define(tree).asClass
val classType = classSymbol.selfType

val classMirror = toolbox.mirror.reflectClass(classType.typeSymbol.asClass)
val ctorSymbol = classType.decl(ru.termNames.CONSTRUCTOR).asMethod
val methodSymb = classType.decl(ru.TermName("foo")).asMethod
val ctor = classMirror.reflectConstructor(ctorSymbol)
val instance = ctor()
val im = toolbox.mirror.reflect(instance)
val foo = im.reflectMethod(methodSymb)
println(foo())  // List("A", "B")
println(methodSymb.returnType)  // List

Why do these code snippets produce different results?

How can we reflect the concrete return type of the foo() method if Cls is defined at runtime using the toolbox?





Reflection check if parametized type is String and Obeject

I am having an issue when checking parameterized types of a parameter. I am using method.getGenericParameterTypes() and casting it to ParameterizedType simply to check if the parameter is the correct Map however when I check the types I get String, ? instead of String, Object, for the string it's easy to check with String.class.equals(type[0]) however for ? doing Object.class.equals(type[1]) will return false. Is there a better way to check if the parameterized type is Object?





Exceptions under DeclaringParameter, GenericParameterAttributes and GenericParameterPosition

System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetEntryAssembly();
Type[] Types = myAssembly.GetTypes();
foreach (Type myType in Types)
{
     if (myType.BaseType == null) continue;                               

     if (myType.BaseType == typeof(Form))
     {
        IEnumerable<Component> x = EnumerateComponents(myType)         
     }
 }

Why under myType I get exceptions and how to solve them?

enter image description here

UPDATE

method which should process myType

public IEnumerable<Component> EnumerateComponents(object formobj)
{
   var l = (from field in formobj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
           where typeof(Component).IsAssignableFrom(field.FieldType)
           let component = (Component)field.GetValue(formobj)
           where component != null
           select component);

            return l;
 }




Invoke static method with access only to the containing object's type

I have a TypeTag for one of several objects and I know that they extend a base trait with a known method signature. I also have access to the method's MethodSymbol if I need it. What I want to do is:

def invokeMyMethod[T: TypeTag](myMethodSymbol: MethodSymbol): String = {
  // I know T has structural type { def myMethod: String }
  // so I want the result of calling T.myMethod but I don't have
  // access to the actual object T, only its type.
}

Since I know the type represents an object, I know that the method is static and so I just need access to the singleton instance to be able to invoke the method. Unfortunately I can't find a way to get from the type to the instance.

I know I can obtain a RuntimeClass instance from a runtimeMirror, but I'm not sure what to do with that class once I have it. It seems to essentially have type AnyRef, so I tried casting it with no luck:

def invokeMyMethod[T: TypeTag]: Any = {
  val runtimeT = runtimeMirror(getClass.getClassLoader).runtimeClass(T)
  runtimeT.asInstanceOf[{ def myMethod: String }].myMethod
  // Error invoking method 'myMethod'
}

I also know I can get a ClassMirror from my ClassSymbol but that only seems to give access to the constructor MethodMirror which doesn't help if my item is an object and not a class:

def invokeMyMethod[T: TypeTag](myMethodSymbol: MethodSymbol): Any = {
  val mirror = runtimeMirror(getClass.getClassLoader)
  val runtimeT = mirror.runtimeClass(T)
  val mirrorT = mirror.reflect(runtimeT)
  mirrorT.reflectMethod(myMethodSymbol)()
  // Expected a member of class Class, you provided value T.myMethod
}

And I know if I had the actual runtime instance of T it would be easy with an InstanceMirror but I can't figure out how to get the InstanceMirror of my object type.





Obtaining serializer for a class in kotlinx.serialization

Assume that C is a serializable class:

@Serializable
class C

I have at least four ways of obtaining serializer for this class.

  1. Companion(?) function. Actually IDEA doesn't let me to go to declaration, so I assume it's a kind of synthetic compiler-plugn-generated function.
val s = C.serializer()
  1. serializer() call with reified type argument:
val s = serializer<C>()
  1. KClass experimental extension:
val c = C()
val s1 = C::class.serializer()
val s2 = c::class.serializer()
  1. serializer() semi-experimental overload:
val c = C()
val s1 = serializer(C::class.createType())
val s2 = serializer(c::class.createType())

The last two ways seem to be more powerful: for example, I may use it for polymorphic serialization getting actual KClass for an instance of abstract type and choosing the correct serializer.

I have several questions:

  1. What ways of obtaining serializer by type actually exist and what ways are preferrable?
  2. As I understand, I may register several serializers for one class, so which one do I get in each of these cases?
  3. Assuming I've registered a custom serializer for a class using @Serializable(with=...), is it possible to obtain a standard serializer for it somehow?