lundi 28 février 2022

Scala reflection: compile akka actor with protobuf

I am trying to compile an Actor with DynamicMessage with Scala Reflection Toolbox

The actor code looks like

import scala.reflect.runtime.universe
import scala.tools.reflect.ToolBox
val toolbox = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
    val actorCode =
  """
    |import akka.actor._
    |import com.google.protobuf._
    |class SimpleActor extends Actor {
    |override def receive: Receive = {
    | case dynamicMessage: DynamicMessage => println("Dynamic message received!")
    | case _  => println("Whatever!")  // the default, catch-all
    |  }
    |}
    |object SimpleActor {
    |def props() : Props = Props(new SimpleActor())
    |}
    |
    |
    |return SimpleActor.props()
    |""".stripMargin
val tree = toolbox.parse(actorCode)
toolbox.compile(tree)().asInstanceOf[Props]

I get the error

reflective compilation has failed:

illegal cyclic reference involving type T
scala.tools.reflect.ToolBoxError: reflective compilation has failed:

illegal cyclic reference involving type T

If I run the code outside of the Toolbox it compiles and works fine. The error is given from the line

case dynamicMessage: DynamicMessage => println("Dynamic message received!")

Anyone knows the nature of this error and how to fix it?





How can I get a type of collection? [duplicate]

Here is the way how I can get a type:

String.class

How can I get a type of collection:

 List<String>




How to get property value of object which is in object array from another class

I want to get property value of an object which is in object array from another class. I tried to use reflection, but I had to do something wrong...

My code:

  //Map.cs

    //in BoardTiles i keep objects of classes which have property "Name" and I want to get it.

    public class Map
        {
            public int Rows { get; private set; }
            private int Cols { get; set; }
            public Object[,] BoardTiles { get; private set; }
            private Floor Floor { get; set; }
            private PlayerTile PlayerTile { get; set; }
            private Sword OldSword { get; set; }
    
    
    
            public Map()
            {
                this.Rows = 10;
                this.Cols = 40;
                this.BoardTiles = new Object[Rows, Cols];
                this.Floor = new Floor();
                this.PlayerTile = new PlayerTile();
                this.OldSword = new Sword("oldSword", 5);
    
            }
//Sword.cs 
//this is what the sword class looks like, object of this class is stored in BoardTiles 

{
    public class Sword : Tile
    {
        public override string Type { get; set; }
        public string Name { get; set; }
        public int Dmg { get; set; }

        

        public Sword(string name, int dmg)
        {
            this.Type = "sword";
            this.Name = name;
            this.Dmg = dmg; 
        }
    }
}

//Program.cs
 case ConsoleKey.Spacebar:
            Console.Clear();

            map.getItem(playerPositionX, playerPositionY);
/*            map.movefill(playerPositionX, playerPositionY);
*/            map.printBoard();
            Console.Write(map.BoardTiles[playerPositionX, playerPositionY]);
            **//Place where i need value of property of object from array of objects** 
            break;

    }
}

I'm doing a dungeon crawler and when the player steps over a tile with an item he can pick the item, so the situation is - player is on the item tile which is an index in an array of objects and I want to know the name of this object. 





ClassNotFoundException and NoClassDefFoundError trying to inspect Spring Boot jar file with java.lang.reflect

I am trying to build a tool that can inspect a specified Spring Boot application packaged as a jar. I am able to list the contents of the jar, and I am able to load and inspect some classes, but others, most importantly our own classes -- those that make up the actual application code -- I cannot inspect and get a ClassNotFoundException when trying to load them. Many, but not all, of those classes are located in BOOT-INF/classes and I have tried both with and without that path in the URLs provided, and with and without that as part of the class name. I also get many NoClassDefFoundError exceptions. If I expand the jar file, the "missing" classes are located where expected under BOOT-INF/classes/

I am not trying to run the application. That works fine with ./gradlew bootrun and I am not trying to create a custom launcher or anything like that, which is all I'm able to find for sample code. Even the SO suggestions are all related to issues running and deploying Spring Boot applications. I'm sure the causes are similar or related, but I don't know how to bridge the gap.

All I want to do is extract all the parameters that have the @Value annotation and report the values of those annotations, for both our code and any dependencies. Ultimately I want to be able to validate our yaml configurations and report on missing configuration values that are missing from those files.

Manifest (lightly redacted):

Manifest-Version: 1.0
Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx
Spring-Boot-Layers-Index: BOOT-INF/layers.idx
Start-Class: com.redacted.redacted.redacted.redacted.redactedApp
 lication
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Spring-Boot-Version: 2.5.8
Specification-Version: 1.0.0
Main-Class: org.springframework.boot.loader.JarLauncher

My class loader is created like this:

final URL url = jarFile.getUrl();
final URLClassLoader urlClassLoader = LaunchedURLClassLoader.newInstance(new URL[] {
    new URL(url.toString() + "BOOT-INF/classes!/"),
    url,
});

I get the class name and try to load (exception handling code not shown):

String name = jarEntry.getName();
int endIndex = name.lastIndexOf(".class");

String className = name.substring(0, endIndex)
        .replace('/', '.').replace("BOOT-INF.classes.", "");

Class<?> loadedClass = urlClassLoader.loadClass(className);

How can I fix the problem loading these classes, or, alternatively, is there another way to extract all parameters with the @Value annotation, for all code and dependencies?





samedi 26 février 2022

"java.lang.IllegalArgumentException: java.lang.ClassCastException@4ce4fde9" when trying to clone the subclass of an abstract class using a copy const

Here is the complete cloning process:

void ghost(){
//accesses player hotbar to grab the in-hand object
int hotbarAccessIndex = game.keyManager.lastNumKey;

//variable toClone is the object grabbed from the hotbar
AbstractSprite toClone = game.player.hotbar.inventoryArray[hotbarAccessIndex];

//Class of toClone is grabbed 
Class toClass = toClone.getClass();

//toClass is used to grab toClone's copy constructor
Constructor toConstruct = null;
try{
  toConstruct = toClass.getDeclaredConstructor(P4Torio.class, toClass);
} catch(NoSuchMethodException e){
  print(e);
}

AbstractSprite clone = null;
try{
  //AbstractSprite[] params = {toClone};
  clone = (AbstractSprite) toConstruct.newInstance(P4Torio.class, toClone);
} catch(Exception e){
  print(e + "\n");
}

I get the exception listed in the title when attempting to do the following:

AbstractSprite clone = null;
try{
  //AbstractSprite[] params = {toClone};
  clone = (AbstractSprite) toConstruct.newInstance(P4Torio.class, toClone);
} catch(Exception e){
  print(e + "\n");
}

Here is the copy constructor of toClone:

API(API other){
super(other.x, other.y, other.size, other.direction, other.path, other.tint);

}

Here is the copy constructor of AbstractSprite:

AbstractSprite(AbstractSprite other){
this.x = other.x; this.y = other.y; 
this.w = other.w; this.h = other.h; 
this.size = other.size;
this.direction = other.direction; this.path = other.path;
this.sprite = other.sprite;
this.col = other.col; this.tint = other.tint;

}

Any ideas?





vendredi 25 février 2022

error "does not contain a definition for 'getProperty'" when trying to set property of generic typed object

void myFunc<M>()
{
    dynamic uploadReq = (M)Activator.CreateInstance(typeof(M));
    uploadReq.getProperty("Credentials").SetValue(null);
}

I have a function where I supply a type, an object of this type is created, and then a property on the object is set to null. I get an error

MyCustomType does not contain a definition for 'getProperty'

How can I fix this?





jeudi 24 février 2022

Adding a @Profile annotation to a component prevents ClassPathScanningCandidateComponentProvider from finding the bean

I have an annotation @LogProperty that can be applied to fields.

package com.foo;

@Component
@ConfigurationProperties("myapp")
public class FooClass {
    @LogProperty
    private String foo = "bar";
...

And some code that is looking for @ConfigurationProperties annotations:

ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(ConfigurationProperties.class));

Set<BeanDefinition> components = scanner.findCandidateComponents("com.foo");
for (BeanDefinition beanDefinition : components) {
    ...
    check-for-LogProperty-annotation-and-do-something()
    ...

This code is then triggered in the run(String... args) method of a CommandLineRunner

With this I'm able to e.g. log the field/value to the console.

myapp: foo=bar

But if I add an arbitrary (e.g. @Profile("buuhh")) to the FooClass the scanning code from above does no longer find the annotated field.

Why does the @Profile annotation prevents it from being found? Is there a way to "fix" this?

I suspect there is a timing issue. But If I debug the code, than the debugger stops at the foo field before the CommandLineRunner is triggered.





Kotlin reflection fails to return function after update to version 1.6.10

I have the following kotlin property declared in a class of my Android app:

private val updateRef: KFunction<*> by lazy {
    dao::class.functions.find {it.name.equals("update", true)}!!
}

Where dao is a reference to a Room DAO interface. Since I've updated kotlin to version 1.6.10 it doesn't work anymore, the following wierd exception is thrown every time I try to execute the code above. The same exception is thrown when I evaluate the expression using Android Studio's EVALUATE tool:

"Incorrect resolution sequence for Java method public open suspend fun count(): kotlin.Int defined in it.kfi.lorikeetmobile.db.dao.TablePriorityDao_Impl[JavaMethodDescriptor@d45ec9a]".

Where count() is a suspend method declared in the DAO interface. But I get this for every DAO class I have in my project and for different methods, so I think the method has nothing to do with the real problem here... I cannot figure out what is happening.

Before the update I had no problems at all. Please help.





Get only the parent fields from an inherited class

I have a class called Stats

public class Stats : ScriptableObject
{
    public double vitality;   
    public double stamina;     
    public double endurance; 
} 

I also have a class that inherits Stats

public class Equipment : Stats
{
    public string name;
    // other fields that define equipment
} 

I want to be able to get all the fields from the instance of Stats that is inherited from Equipment

So I added this in an Interface class

    public void AddStats(Equipment equippedItem)
    {
        Stats stats = equippedItem as Stats;
        if (stats != null)
        {
            GetPropertyValues(stats);
        }
    }
   public static void GetPropertyValues(System.Object obj)
   {
        Type t = obj.GetType();
        FieldInfo[] fis = t.GetFields(BindingFlags.Instance | BindingFlags.Public);
        foreach (var fieldInfo in fis)
                Debug.Log(fieldInfo.FieldType + " " + fieldInfo.Name + " " + fieldInfo.GetValue(obj));
   }

The issue is that it is getting all the fields from the Equipment as well.

How could I make it so that only gets the fields from Stats?





mercredi 23 février 2022

How do I fetch the overridden member of a sealed trait via reflection?

I'm trying to write a generalised function that takes a Type of SomeSealedClass and uses reflection to return a list of values overridden by the trait's child classes/objects.

sealed abstract class Sealed(val name: String)
object Sealed {
    case object One extends Sealed("first one")
    case object Two extends Sealed("second one")
    case object Three extends Sealed("third one")
}

def expand(sealed: Type): List[String] = ???

I need the function expand to return List("first one", "second one", "third one") but only if Sealed has a field called name.

I don't have access to the type because the caller is building the type object from a string using Class.forName(). So, I cannot create instance mirrors to fetch the value of the name field from each of the subclasses.

I'm starting to think that this is not actually possible but cannot figure out why. Those values are fixed. So, it should be simple to extract them without the type, isn't it?





Type checking a PHP function before calling it

I have a webservice that will be used something like that:

GET http://localhost/services/sum?a=1&b=2

This will resolve directly (ignore details like authorization) on a function call defined something like this:

class Services {
    public function sum(int $a, int $b) {
        return $a + $b;
    }
}

Now, if they user calls GET http://localhost/services/sum?a=abc&b=2, this is a PHP type error. Before calling the sum function, I want to "type check" the arguments and report what's wrong. In this case, the response would be something like

"errors" {
    "a": {
        "type_mismatch": {
            "expected": "int",
            "received": "string",
        }
    }
}

For this purpose, I wrote this function:

function buildArguments(array $arguments, $service)
{
    $reflectionMethod = new \ReflectionFunction($service);
    $reflectionParameters = $reflectionMethod->getParameters();
    $missingArguments = [];
    $typeMismatch = [];
    foreach ($reflectionParameters as $reflectionParameter) {
        $name = $reflectionParameter->getName();
        if (!array_key_exists($name, $arguments) && !$reflectionParameter->isOptional()) {
            $missingArguments[] = $reflectionParameter->getName();
        } else if ((is_null($arguments[$name] ?? null) && !$reflectionParameter->getType()->allowsNull()) ||
            !($reflectionParameter->getType()->getName() == gettype($arguments[$name]))) {
            $typeMismatch[$name] = [
                'received' => gettype($arguments[$name]),
                'expected' => $reflectionParameter->getType()->getName()
            ];
        }
    }
    $errors = [];
    if (!empty($missingArguments)) {
        $errors['missing_argument'] = $missingArguments;
    }
    if (!empty($typeMismatch)) {
        $errors['type_mismatch'] = $typeMismatch;
    }
    if (empty($errors)) {
        return true;
    } else {
        var_dump($errors);
        return false;
    }
}

It works well for strings:

function concat(string $a, string $b) {
    return $a . $b;
}
buildArguments(['a' => 'x', 'b' => 'y'], 'concat'); //ok!
buildArguments(['a' => 'x'], 'concat'); // missing_argument: b
buildArguments(['a' =>  1, 'b' => 'y'], 'concat'); //type mismatch: a (expected integer, got string)

It immediately falls apart for int:

function sum(int $a, int $b): int
{
    return $a + $b;
}
buildArguments(['a' => 1, 'b' => 2], 'sum');
//type mismatch! expected "int" received "integer"

I only need this to work for simple structures: ints, string, untyped arrays, no need to check object, inheritances, interfaces and whatnot. I could just add a "if int then integer" but I have a feeling there will be a bunch of gotchas regarding nullables and optionals. Is there a clever way of achieving this?

The TypeError doesn't offer any help in that regard, only a stringified message, maybe I can "manually" call whatever procedure PHP calls that throws the TypeError?





Load Android Native library with Java reflection

I'm trying to load an Android native library with Java reflection, but at runtime the library is not found. Normally i load a native library with:

System.loadLibrary("mylib");

and everything works as expected. Now i try to call the loadLibrary method with reflection, like this:

Class<?> system = Class.forName("java.lang.System");
Method loadLibrary = system.getDeclaredMethod("loadLibrary", String.class);
loadLibrary.invoke(null, "mylib");

but at runtime i get:

Caused by: java.lang.UnsatisfiedLinkError: Library mylib not found; tried [/system/lib64/libmylib.so, /vendor/lib64/libmylib.so]
    at java.lang.Runtime.loadLibrary0(Runtime.java:1001)
    at java.lang.System.loadLibrary(System.java:1530)
    at java.lang.reflect.Method.invoke(Native Method)

It seems like with reflection loadLibrary look for the library in the wrong path. These /system/lib64:/vendor/lib64 are the paths of java.library.path property, but it does not look inside the apk. Of course the library is present in the final apk, and it's in the right place, for the right ABI.

NOTE

I can't use

System.load("absolute-path-to-lib/mylib.so");

because from where i'm calling this i don't have the path available, i don't have any Context or Application available yet to retrive the path.

Do you have any idea how to force loadLibrary to search in the current apk ? Thank you!





mardi 22 février 2022

How do I fetch the override member of a sealed trait via reflection?

I'm trying to write a generalised function that takes a Type of SomeSealedClass and uses reflection to return a list of values overridden by the trait's child classes/objects.

sealed abstract class Sealed(val name: String)
object Sealed {
    case object One extends Sealed("first one")
    case object Two extends Sealed("second one")
    case object Three extends Sealed("third one")
}

def expand(sealed: Type): List[String] = ???

I need the function expand to return List("first one", "second one", "third one") but only if Sealed has a field called name.

I don't have access to the type because the caller is building the type object from a string using Class.forName(). So, I cannot create instance mirrors to fetch the value of the name field from each of the subclasses.

I'm starting to think that this is not actually possible but cannot figure out why. Those values are fixed. So, it should be simple to extract them without the type, isn't it?





lundi 21 février 2022

URI for third party dependency

My Question:

Is it possible to get a Uri from an import of a third party dependency?

Question Context:

I am trying to get a list of classes accessed with the following.
import com.name.*

In the context in which I want to use it, I will not be able to use third party dependencies. I do however need to find all classes associated with a third party dependency import.

I have found one such answer to my issue in the following code, provided by the user tirz.

public static List<Class<?>> getClassesForPackage(final String pkgName) throws IOException, URISyntaxException {
    final String pkgPath = pkgName.replace('.', '/');
    final URI pkg = Objects.requireNonNull(ClassLoader.getSystemClassLoader().getResource(pkgPath)).toURI();
    final ArrayList<Class<?>> allClasses = new ArrayList<Class<?>>();

    Path root;
    if (pkg.toString().startsWith("jar:")) {
        try {
            root = FileSystems.getFileSystem(pkg).getPath(pkgPath);
        } catch (final FileSystemNotFoundException e) {
            root = FileSystems.newFileSystem(pkg, Collections.emptyMap()).getPath(pkgPath);
        }
    } else {
        root = Paths.get(pkg);
    }

    final String extension = ".class";
    try (final Stream<Path> allPaths = Files.walk(root)) {
        allPaths.filter(Files::isRegularFile).forEach(file -> {
            try {
                final String path = file.toString().replace('\\', '.');
                final String name = path.substring(path.indexOf(pkgName), path.length() - extension.length());
                allClasses.add(Class.forName(name));
            } catch (final ClassNotFoundException | StringIndexOutOfBoundsException ignored) {
            }
        });
    }
    return allClasses;
}

The problem I have with the code above is that where final URI pkg is assigned. This works with a package that exists within the project, but if an import for a third party dependency is used this throws a NullPointerException. Is it possible to make this code work for third party dependencies? Might this require some reference to an .m2 folder or other library resource?





How to tell whether an invoked method has a method body or not at runtime in an Android app/Java application?

I hope to know if an invoked method has a Java method body at runtime in an Android app/Java application.

For example, in the following code, a method f is invoked

obj.f();

To know whether f has a method body, I use reflection to get its modifiers and then check if the method is a native method:

int modifiers = obj.getClass().getMethod("f", new Class[] {}).getModifiers();
if(Modifier.isNative(modifiers)) {
   // No method body
} else {
   // has method body
}

My question is: except native methods, are there any other possible cases in which an invoked method does not have a Java method body? Abstract or interface methods are not possible since at runtime, what have been invoked must be concrete methods that implement them.





How to initialize static fields in subclasses

I have an abstract base class, and subclasses who all have an automatically generated Instance static field of their own type, done through using genericity "in between" the base and sub classes (see code below).

When those instances are created, I register them in a dictionary based on specific "identifying" fields overwritten in subclass constructors, in order to access them somewhere else in the code.

I could register them in their constructors, however I don't want to have to drag and copy/paste this same bit of code in every such subclass in order to register them.

public abstract class BaseClass
{
        // Declaration of fields and methods
}

public class GenericBaseClass<T> : BaseClass where T : GenericBaseClass<T>
{
        private static T instance = ((T) Activator.CreateInstance(typeof(T), true)).Register();
        public static T Instance => instance;

        public T Register()
        {
                // Registers Instance in a dictionary.
        }

}

public class Subclass1 : GenericBaseClass<Subclass1>
{
        private Subclass1()
        {
                // Modification of protected fields.
        }
}

Doing this enables me to call Subclass1.Instance, and by doing so, this instance gets registered in my dictionary, however it doesn't get registered before I try to access it, and only Subclass1 gets that treatment, not other subclasses.

I followed this answer https://stackoverflow.com/a/34726769/13738641 (in the updated section) and made a static constructor for BaseClass and for GenericBaseClass hoping it would initialize static fields for those subclasses, to no avail.

It appears from debugging that the BaseClass static constructor is indeed called, and it does fetch the right subclasses, but it doesn't throw an error, nor does it calls the subclass (static) constructors. Now I could be going crazy, but I could have sworn it worked once before I tried modifying something before reverting back to that, only for it not to work anymore.

I've tried adding a static constructor to the generic class which I hoped would be called once for each subclass, but this constructor only gets called once (when I access some subclass's instance in order to trigger the BaseClass static constructor call).

Any suggestion on what to do to achieve this? I accept suggestion on other ways to achieve something similar (i.e. keep a dictionary generated at runtime with instances of my classes), the subclasses being singletons isn't critical, so maybe I could register constructors instead of instances in the dictionary? I have no idea if that is even possible, with each constructor returning a different type.





dimanche 20 février 2022

error when invoking Activator.CreateInstance with IEnumerable parameter filtered with LINQ

tl;dr:
When I filter output of ServiceProvider.GetServices(Type) for some reason I cannot use it later for constructing object with reflection. What am I missing?

Complete console application with DependencyInjection as its only dependency:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;

namespace GenericsExperiment
{
    class Program
    {
        static void Main(string[] args)
        {
            //setup DI
            var services = new ServiceCollection();
            services.AddTransient<ISomeHandler<Message>, MessageHandler>();
            services.AddTransient<ISomeHandler<Message>, MessageHandler2>();
            var serviceProvider = services.BuildServiceProvider();

            //get all types of ISomeHandler<Message>
            var messageType = typeof(Message);
            var handlerType = typeof(ISomeHandler<>);
            var handlerGenericType = handlerType.MakeGenericType(messageType);
            var handlers = serviceProvider.GetServices(handlerGenericType);

            //Create SomeService type and pass handlers to constructor
            var someServiceType = typeof(SomeService<>);
            var someServiceGenericType = someServiceType.MakeGenericType(messageType);
            var concreteService = Activator.CreateInstance(someServiceGenericType,
                handlers) as SomeService<Message>;
            Console.WriteLine("Concrete type with all handlers created");


            //same as above but this time use primitive filtering:
            var filteredHandlers = serviceProvider.GetServices(handlerGenericType)
                .Where(h => h.GetType().FullName.Contains("MessageHandler2")).ToList();

            //this line throws exception System.MissingMethodException: Constructor on type
            //'GenericsExperiment.SomeService`1[[GenericsExperiment.Message, GenericsExperiment,
            //Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found.
            var concreteServiceWithFilteredHandlers = Activator.CreateInstance(someServiceGenericType,
                filteredHandlers) as SomeService<Message>;

        }
    }

    public class Message { public string Value { get; set; } }

    public interface ISomeHandler<in T> {
        void Handle(T message);
    }

    public class MessageHandler : ISomeHandler<Message> {
        public void Handle(Message message)=>Console.WriteLine($"handled: {message.Value}");
    }

    public class MessageHandler2 : ISomeHandler<Message> {
        public void Handle(Message message) => Console.WriteLine($"handled by messageHandler 2: {message.Value}");
    }

    public class SomeService<T> where T : class {
        public SomeService(IEnumerable<ISomeHandler<T>> handlers) { }

        public void DoSomethingWithHandlers() => throw new NotImplementedException();
    }
}




Using Kotlin reflection how to determine which constructor parameters were given as `val`?

Simple case A (no problem here)

class A(val title: String)

For instance a, we will get the parameters list from a.javaClass.kotlin.primaryConstructor!!.valueParameters.

Simple case B (no problem here)

class B(titleRaw: String) {             // no val
  val titleFinal = titleRaw.uppercase() // the property has different name
}

We can determine that the titleRaw parameter does not create a property because there is no titleRaw property on the object. We will use valueParameters and memberProperties to detect that.

Difficult case:

class C(title: String) {        // no val
  val title = title.uppercase() // property with the same name
}

How to detect that the title property does not return the value of the title parameter?

A little background

Having an instance of a class, I want to know what constructor argument values it was instantiated with. If that's not possible (the primary constructor takes arguments that aren't properties), I'd like to throw an exception.





Creating List in runtime using Java reflection

I am trying to solve the problem of creating a List in runtime. I created method

private <GT, LT> LT getList(Class<GT> genericType, Class<LT> listLype) throws Exception {
    Constructor<LT> c = listLype.getConstructor();
    ...
    ???
}

where LT - type of List I want to create (ArrayList, LinkedList, etc), and GT - generic type of List. How can I createLT<GT> List?





vendredi 18 février 2022

How to obtain superclass of a reflected class in Kotlin?

If Kotlin disallows multiple inheritance, then why KClass<*>.superclasses return a list? How to find that single superclass?





Is there a way to find the max length of a property among all elements in ICollection

So i need to make ICollection into a table, column width must be determined by max length of value of property. I currently use this

        private static int GetWidth<T>(PropertyInfo prop, ICollection<T> source)
        {
            int width = 5;
            foreach (var element in source)
            {
                if (prop.GetValue(element).ToString().Length > width)
                {
                    width = prop.GetValue(element).ToString().Length;
                }
            }

            return width;
        }

but it does not work at all, maybe someone knows a way to do it? Edit: solved, used Math.Max(5, source.Max(e => prop.GetValue(e).ToString().Length)) instead





How to get the value of a property and assign it to another property using reflection C#

I get a Json response and deserialize it into one of the models. I do not know the data type in advance, but i can get its name from the response and deserialize it using reflection. Then I try to assign a response(response.data) to the CommonModel field, but I get an error "Object does not match target type"

void Method(string typeName, string json)
    {
        CommonModel commonModel = new();
        Type modelType = Type.GetType($"{typeName}");
        var modelInstance = Activator.CreateInstance(modelType); //create instance of model, for example Model1

        Type openType = typeof(ResponseModel<>);
        Type[] tArgs = { modelType };
        Type target = openType.MakeGenericType(tArgs); //create instance of ResponseModel<>, for example ResponseModel<Model1>

        var methods = typeof(JsonSerializer);
        var method = methods.GetMethods().FirstOrDefault(w => w.IsGenericMethod && w.Name == "Deserialize" && w.GetParameters().Any(x => x.ParameterType.Name == "String"));
        MethodInfo generic = method.MakeGenericMethod(target); //Create JsonSerializer.Deserialize<T>(json), for example Deserialize<ResponseModel<Model1>>
        var instance = Activator.CreateInstance(target);
        var model = generic.Invoke(instance, new object[] { json, null }); //invoke deserialize method

        var data = model.GetType().GetProperty("data").GetValue(modelType, null); // Exception "Object does not match target type"
        //How do I get the model.data property and assign it to commonModel.{propertyName}
    }

public class Response<T>
    {
       public string request_id { get; set; }
       public T data { get; set; }
    }

   Public class Model1
{
   public string Field1 { get; set; }
   public string Field2 { get; set; }
}

Public class Model2
    {
       public string Field3 { get; set; }
       public string Field4 { get; set; }
    }

Public class CommonModel
        {
           public Model1 Model1 { get; set; }
           public Model2 Model2 { get; set; }
        }

As a T i use Model 1 or Model2.





How to get the value of a property and assign it to another property using reflection C#

I have some classes

public class Response<T>
    {
       public string request_id { get; set; }
       public T data { get; set; }
    }



   Public class Model1
{
   public string Field1 { get; set; }
   public string Field2 { get; set; }
}

Public class Model2
    {
       public string Field3 { get; set; }
       public string Field4 { get; set; }
    }

Public class CommonModel
        {
           public Model1 Model1 { get; set; }
           public Model2 Model2 { get; set; }
        }

As a T i use Model 1 or Model2.

For Example i have Instance of Model1

var modelInstance = Activator.CreateInstance(modelType);

But when i try

var result  = responseObject.GetType().GetProperty("data").GetValue(modelInstance);

I get "Object does not match target type." Exception

How can i get data property from responseObject and set in to CommonModel.{PropertyName} using reflection





jeudi 17 février 2022

Generic Parameter Requires type "Nothing" when T is type "Any"

I am a new Kotlin programmer, and I am having a problem relating to generics

In the following code, I am getting an error with it.get(this) "Type mismatch. Required: Nothing. Found: Any.

inline fun <reified T : Any> Any.getPropertiesWithType() =
    this::class.memberProperties
        .filter { it.returnType.isSubtypeOf(T::class.starProjectedType) }
        .map {
            it.isAccessible = true
            it.get(this) as T
        }

This is confusing because memberProperties returns a Collection<KProperty1<T, *>> where T is the type of this, which is Any in my case. KProperty1.get() takes one argument of that same type T, so I would expect Any could be passed without an issue.

One thing I noticed is that it in the filter and map are both type KProperty<out Any, *>> but memberProperties does not have the out variance.

If I replace this::class with this.javaClass.kotlin, it works without an error, but that seems like a very bad way to go about this.

If anyone knows a way to fix this, or an entirely different strategy, it would be much appreciated. I am new to Kotlin and still do things in the Java way sometimes.





Failure to discover property with reflection

Taking the following minimal example:

type IMyInterface =
    interface
        abstract member Name: string with get
    end

let testInstance =
    { new IMyInterface with
        member _.Name = "Hello Word" }

I would have naively expected a call to testInstance.GetType().GetProperties() to contain a PropertyInfo element corresponding to Name.

However, only an empty array is returned.

Using testInstance.GetType().GetProperty("Name") yields no better as it simply returns a <null> object.

More confusing still, Visual Studio 2022 IntelliSense lists Name as a valid property (as I'd expect).

How can I get a PropertyInfo corresponding to the Name property?





Creating List in runtime using java refliction

I am trying to solve the problem of creating a List in runtime. I created method

    private <GT, LT> LT getList(Class<GT> genericType, Class<LT> listLype) throws Exception {
    Constructor<LT> c = listLype.getConstructor();
    ...
    ???
}

where LT - type of List I want to create (ArrayList, LinkedList, etc), and GT - generic type of List. How can I createLT<GT> List? Thanks for any help.





How to find the KClass of the owner of a companion object?

I'm trying to get the class that owns a companion object so I can create loggers with inline technique inside a companion object but referencing the main class that is being logged and not the companion object.

The problem is that I can't find a way to get the owner of the companion object, how can I do it?

fun Logger(c: Class<*>): Logger {
    var c2 = c
    val k = c.kotlin
    if (k.isCompanion) {
        c2 = k.<opposite of what companionObject does>.java
    }

    // Calls a factory, reuse the same instance if it already exists
    return RootLogger.getChild(c2)
}

@Suppress("NOTHING_TO_INLINE")
inline fun Logger(): Logger {
    return Logger(MethodHandles.lookup().lookupClass())
}

The intended use-cases:

A:

class SomeClass {
    companion object {
        // Logger is inside a companion object
        // But it must be the same as if it were created directly inside `SomeClass`
        private val log = Logger()
    }

    fun someFun() = log.info("Hello")
}

B:

// can be object or anything else
class SomeClass {
    // The same object is returned to all instances and would be the same object
    // as if it were inside a companion object
    private val log = Logger()

    fun someFun() = log.info("Hello")
}




How do I get property name with class name without creating new obj like GetName(MyClass.Name) = "MyClass.Name"

Cant understand how simple do it

public class MyClass
{
    public string FName;
    public double DoSumma;
}

I wish simple Method like this

public string GetName(...)
{
 return ...
}
...
string propertyname = GetName(MyClass.DoSumma);
// propertyname = "MyClass.DoSumma"
...

I know about

$"{nameof(MyClass)}.{nameof(MyClass.DoSumma)}"

Help?





mercredi 16 février 2022

How can I modify a reflection object in golang when type is interface type

I try to set a map type with reflection.

However, the program will panic that is "using unaddressable value".

I call CanSet() func that return false that represent it cannot set.

I can get a addressable value if value type isn't interface type.

I know that I should call Elem() twice for getting addressable value but it still panic.

Why the result is different?

How can I fix this in the general case?

The following is example code

func main() {
    var obj = Test{}
    TestFunc(obj)
}

func TestFunc(obj interface{}) {
    objValueType := reflect.ValueOf(&obj).Elem().Elem()
    infoValueType := objValueType.FieldByName("TestInfo")
    mapValueType := infoValueType.FieldByName("TestMap")

    maps := map[string]*TestInfoDetail{}
    maps["1111"] = &TestInfoDetail{Key: "AAAA"}
    maps["2222"] = &TestInfoDetail{Key: "BBBB"}
    mapType := reflect.ValueOf(maps)

    mapValueType.Set(mapType)
    mapValueType.SetMapIndex(reflect.ValueOf("3333"), reflect.ValueOf(&TestInfoDetail{Key: "WOWO"}))
    maps, ok := mapValueType.Interface().(map[string]*TestInfoDetail)
    if ok {
        for _, item := range maps {
            fmt.Println(item.Key)
        }
    }
}

Thanks.





NotNullAttribute missing when checking by reflection

What we are trying to do is to list all properties of the class with NotNull attribute. The one from .NET, not from JetBrains. Unfortunately, it looks like NotNullAttribute is removed during the compilation process (or on some other stage) and it can't be observed in the runtime.

Does anyone know why does it happen? Can't find an explanation on the internet/MSDN.

Here is a test that can easily reproduce it. It fails on the second assertion.

public class Tests
{
    public class Foo
    {
        [NotNull, Required] public string? Bar { get; set; }
    }

    [Test]
    public void GetAttributesTest()
    {
        var type = typeof(Foo);
        var property = type.GetProperties()[0];

        Attribute.IsDefined(property, typeof(RequiredAttribute)).Should().BeTrue();
        Attribute.IsDefined(property, typeof(NotNullAttribute)).Should().BeTrue();
    }
}




Performance difference between getDeclaredMethod() and getDeclaredMethods() with different levels of class inheritance

I hope to find the declaring class of a method in Android. The basic idea is to find if the target method is declared in a class. If not, I will recursively find the target method in its super classes. For a specific reason, efficiency matters. So I have two implementations and I compared their performance differences.

Version 1: use the API Class.getDeclaredMethod to check if a method exists in a class. If not, NoSuchMethodException will be thrown.

public Class getDeclaringClass1(Class cls, String mtdName, Class[] paraTypes) {
        Class declaringCls = null;
        try {
            declaringCls = cls.getDeclaredMethod(mtdName, paraTypes).getDeclaringClass();
        } catch (NoSuchMethodException | SecurityException e) {
            Class supr = cls.getSuperclass();
            if(supr != null) declaringCls = getDeclaringClass1(supr, mtdName, paraTypes);
        }
        return declaringCls;
}

Version 2: Manually check if a method is declared in a class using Class.getDeclaredMethods. We will match each method one by one with the method name and parameter types.

public Class getDeclaringClass2(Class cls, String mtdName, Class[] paraTypes) {
        Class declaringCls = null;
        Method[] methods = cls.getDeclaredMethods();
        boolean containsMtd = false;
        for(Method method: methods) {
            if(method.getName().equals(mtdName)) {
                boolean allEqual = true;
                for(int i=0; i< method.getParameterTypes().length; i++) {
                    if(! method.getParameterTypes()[i].equals(paraTypes[i])) {
                       allEqual = false;
                       break;
                    }
                }
                if(allEqual) {
                    containsMtd = true;
                    declaringCls = cls;
                    break;
                }
            }
        }
        if(! containsMtd) {
           Class supr = cls.getSuperclass();
           if(supr != null) declaringCls = getDeclaringClass2(supr, mtdName, paraTypes);
        }
        return declaringCls;
}

I made some interesting observations when testing the efficiency of these two versions. Basically I created several empty classes C, CC, CCC, CCCC. Their relationships are

CC extends C
CCC extends CC
CCCC extends CCC

All these classes does not declare any methods and I use the toString method as the target method. I testing two getDeclaringClass with a loop of 10000 times:

start = System.currentTimeMillis();
for(long i=0; i<10000; i++) {
     getDeclaringClass(cls, "toString", new Class[0]).getName()); // getDeclaringClass will be set to version 1 or 2
}
end = System.currentTimeMillis();
System.out.println((end - start) + "ms");

Here are the results:

cls Version 1 Version 2
C 1168ms 1632ms
CC 2599ms 1397ms
CCC 3495ms 1680ms
CCCC 4908ms 1559ms

We can see that version 1's performance drops significantly when we have more levels of class inheritance. But version 2's performance does not change a lot.

So what makes the difference between version 1 and 2? What makes version 1 so slow?





mardi 15 février 2022

C# create instance of abstract using reflection

I met a task in which it is necessary to create an instance of an abstract class using reflection on C#. At the same time, it is forbidden to create heirs.

It is clear that it is forbidden to create such instances, but reflection helps to overcome this. The answers were advised to look in the source codes on the referencesource site, to look for something like an internal call to the constructor through reflection. A hint in the task: need to find a method in the framework that directly deals with calling the constructor and simulate its logic without unnecessary checks. But I can't find. I find how to create instance of abstract class, but without initializing variables.

How can create such an instance so that class variables with values, if they exist are also initialized?





JBoss 7 startup in standalone mode

I am trying to run Jboss in standalone mode after downloading the zip file and extracting it. I run the standalone.bat script and get the below error.

Calling "D:\Software\JBoss\jboss-as-7.1.1.Final\jboss-as-7.1.1.Final\bin\standalone.conf.bat"
===============================================================================

  JBoss Bootstrap Environment

  JBOSS_HOME: D:\Software\JBoss\jboss-as-7.1.1.Final\jboss-as-7.1.1.Final

  JAVA: C:\Program Files\Java\jdk-11.0.13\bin\java

  JAVA_OPTS: -XX:+TieredCompilation -Dprogram.name=standalone.bat -Xms64M -Xmx512M -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Djava.net.preferIPv4Stack=true -Dorg.jboss.resolver.warning=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djboss.server.default.config=standalone.xml

===============================================================================

Exception in thread "main" javax.xml.transform.TransformerFactoryConfigurationError: Provider com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl could not be instantiated: java.lang.reflect.InvocationTargetException
        at java.xml/javax.xml.transform.FactoryFinder.newInstance(FactoryFinder.java:181)
        at java.xml/javax.xml.transform.FactoryFinder.find(FactoryFinder.java:257)
        at java.xml/javax.xml.transform.TransformerFactory.newInstance(TransformerFactory.java:126)
        at __redirected.__TransformerFactory.<clinit>(__TransformerFactory.java:66)
        at __redirected.__JAXPRedirected.initAll(__JAXPRedirected.java:82)
        at org.jboss.modules.Module$1.run(Module.java:85)
        at org.jboss.modules.Module$1.run(Module.java:72)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at org.jboss.modules.Module.<clinit>(Module.java:72)
        at org.jboss.modules.Main.main(Main.java:255)
Caused by: java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
l.java:45)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
        at java.xml/javax.xml.transform.FactoryFinder.newInstance(FactoryFinder.java:169)
        ... 9 more
Caused by: javax.xml.parsers.FactoryConfigurationError: Provider __redirected.__SAXParserFactory could not be instantiated: java.lang.reflect.InvocationTargetException
        at java.xml/javax.xml.parsers.FactoryFinder.newInstance(FactoryFinder.java:198)
        at java.xml/javax.xml.parsers.FactoryFinder.newInstance(FactoryFinder.java:147)
        at java.xml/javax.xml.parsers.FactoryFinder.find(FactoryFinder.java:226)
        at java.xml/javax.xml.parsers.SAXParserFactory.newInstance(SAXParserFactory.java:147)
        at java.xml/jdk.xml.internal.JdkXmlUtils.getSAXFactory(JdkXmlUtils.java:379)
        at java.xml/jdk.xml.internal.JdkXmlUtils.<clinit>(JdkXmlUtils.java:118)
        at java.xml/com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.<init>(TransformerFactoryImpl.java:251)
        ... 14 more
Caused by: java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
        at java.xml/javax.xml.parsers.FactoryFinder.newInstance(FactoryFinder.java:187)
        ... 20 more
Caused by: java.lang.NullPointerException
        at __redirected.__RedirectedUtils.loadProvider(__RedirectedUtils.java:94)
        at __redirected.__RedirectedUtils.loadProvider(__RedirectedUtils.java:87)
        at __redirected.__SAXParserFactory.<init>(__SAXParserFactory.java:102)
        ... 25 more
Press any key to continue . . .

I looked here and removed the MaxPermSize option from standalone.conf.bat file but it did not resolve my issue, I am using Java 11. Before removing MaxPermSize option i was getting error Java HotSpot(TM) 64-Bit Server VM warning: Ignoring option MaxPermSize; support was removed in 8.0 support was removed in 8.0. Please advise.





lundi 14 février 2022

Micronaut AOP on package to capture execution time of each method

To capture logTime of each controller call, I added @LogTime annotation for package level but it is not working. I am not able to figure out why it is working with ElementType.TYPE at class level annotation but not with ElementType.PACKAGE at package level. Could you please help?

package com.test.aop;

import io.micronaut.aop.Around;
import io.micronaut.context.annotation.Type;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PACKAGE})
@Around
@Type(LogTimeInterceptor.class)
public @interface LogTime {
}

LogTimeInterceptor

package com.test.aop;

import io.micronaut.aop.MethodInterceptor;
import io.micronaut.aop.MethodInvocationContext;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

@Singleton
public class LogTimeInterceptor implements MethodInterceptor<Object, Object> {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogTimeInterceptor.class);

    @Override
    public Object intercept(MethodInvocationContext<Object, Object> context) {
        var timer = new StopWatch(context.getDeclaringType().getSimpleName() + "." + context.getName());
        try {
            timer.start();
            return context.proceed();
        } finally {
            timer.stop();
            LOGGER.info("StopWatch Task name:{} running time:{} sec", timer.getId(), timer.getTotalTimeSeconds());
        }
    }
}

package-info.java

@LogTime
package com.tet.controllers;

import com.test.aop.LogTime;




samedi 12 février 2022

Can a java object have attributes of a parent class object without duplicating the data

I am building an app with data "parent" classes that hold some attributes, and inheriting "child" classes that hold other attributes, but can also directly refer to the parent's attributes. The plan is to add some kind of unique prefix to the parent's attributes in the child to make sure there can be no name collisions with the child's attributes, but also more importantly to allow a child to extend more than one parent class.

Pseudocode would look something like this:

    public class Parent1{
        int a;
        public Parent1(int a){
            this.a=a;
        }
    }
    public class Parent2{
        int a;
        public Parent2(int a){
            this.a=a;
        }
    }
    public class Child{
        int b;
        public Child(int b,Parent1 p1,Parent2 p2){
            this.b=b;
            attributes.add("p1_"+p1.attributes);
            attributes.add("p2_"+p2.attributes);
        }
    }
    Child C=new Child(3,new Parent1(1),new Parent2(2));
    print(C.p1_a, C.p2_a, C.b);

The important thing to understand is that I want to avoid duplicating variables in memory, be able to use this with reflection so that I can access child s parent attributes from user input, as well as minimize code adjustments when adding new attributes to parents.

I understand that what I am trying to do could relatively easily be done by redefining each possible parent attribute in the child, essentially doing C.get_P1_A(), but I would like to avoid having to change the child code every time a new attribute gets added to a parent, and this would also complicate using reflection.

I have a suspicion what I am trying to do is impossible in Java (or at least I don't know a way to do it), so if that is the case, I am willing to drop being able to use reflection or not having to make adjustments while adding new attributes.





jeudi 10 février 2022

Consume http request data - Java Spring

Good night,

I need to get some information from a given http request made through a period:

For example:

Project name : account

Name of end-point : account/v1/login

Name of IP request : 192.168.0.0

Date and time of request access : 2022-02-09 - 21:33:00

In the example below I can get the IP of the machine that made the request and the current date and time.

I need help on how I can get project name (account) and endpoint name (account/v1/login)

Can you help me? How to do with Java Reflection?

enter image description here





what is the best way to check if a string is date value?

Reflection does not seem to be working for time. What is the best approach here?

package main

import (
    "fmt"
    "reflect"
    "time"
)

func main() {
    stringDate := "07/26/2020"

    // parse string date to golang time
    t, _ := time.Parse("01/02/2006", stringDate)

    ts := ""

    ts = t.String()

    v := reflect.ValueOf(ts)

    fmt.Println(ts) // prints "2020-07-26 00:00:00 +0000 UTC"

    fmt.Println(v.Type()) //  prints "string". How do I get this to time.Time ?

}




mercredi 9 février 2022

NoSuchMethodException was thrown when using reflection in Android

Suppose I have two interfaces IUserManager and BBBB declared under package android.os:

package android.os;

public interface IUserManager  {
    void foo();
}
package android.os;


public interface BBBB {
    void foo();
}

Suppose I hope to use refection to get the foo methods defined in them:

line 1: BBBB.class.getDeclaredMethod("foo", new Class[] {});
line 2: IUserManager.class.getDeclaredMethod("foo", new Class[] {});

Why an exception java.lang.NoSuchMethodException: android.os.IUserManager.foo [] is thrown at line 2?





mardi 8 février 2022

C# Reflection- using FieldInfo.SetValue to set a struct field to null safe?

If you use C# reflection to set a (non-nullable) value-type field to null, it appears to accept that and just sets the default value. But since this behavior is slightly unexpected (I'd expect an exception) and I can't find any docs describing this behavior, I want to know if this is safe. Or am I relying on some undocumented / undefined behavior?

Example:

using System;
using System.Reflection;
                    
public class Program
{
    public static void Main()
    {
        FieldInfo pointField = (typeof(ClassWithAPoint)).GetField("point");
        
        ClassWithAPoint classWithAPoint = new ClassWithAPoint();
        classWithAPoint.point.x = 1;
        classWithAPoint.point.y = 2;

        //This works to create a default Point struct (0, 0).  But is this safe?
        pointField.SetValue(classWithAPoint, null);
        
        
        //Prints: "Point = 0, 0"
        Console.WriteLine($"Point = {classWithAPoint.point.x}, {classWithAPoint.point.y}");
    }
    
    public struct Point
    {
        public int x;
        public int y;
    }
    
    public class ClassWithAPoint
    {
        public Point point;
    }
}




Java Record - Tests - Modify Fields

I have a framework used exclusively for testing that sets fields at runtime. The purpose is to set up test cases. Looking forward to upgrading to Java 14+ records I am noticing that existing utilities such as ReflectionTestUtils.setField and PropertyAccessorFactory.forDirectFieldAccess which work on normal private final fields, do not work for record fields.

Is this a limitation of the JVM, or is a limitation of these utilities?





lundi 7 février 2022

How to get the MethodInfo of a Java 14 method reference?

I'm essentially asking the same as this old question, but for Java 14 instead of Java 8. To spare answerers the trouble of navigating to the old question, I'll rephrase it here. I want to get the name of a function from a referenced method. The following Java code should give you the idea:

public class Main
{
    public static void main(String[] args)
    {
       printMethodName(Main::main);
    }

    private static void printMethodName(Consumer<String[]> theFunc)
    {
        String funcName = // somehow get name from theFunc
        System.out.println(funcName)
    }
 }

The equivalent in C# would be:

public class Main
{
    public static void Main()
    {
        var method = Main.Main;
        PrintMethodName(method)
    }

    private static void PrintMethodName(Action action)
    {
        Console.WriteLine(action.GetMethodInfo().Name);
    }
}

According to the accepted answer of the old question, this was not possible in Java 8 without considerable work, such as this solution. Is there a more elegant solution in Java 14?





Java: Is there a way to have a method to get the calling method name?

To get the current method name we can use the following:

new Object(){}.getClass().getEnclosingMethod().getName();

which should be called from within the method body.

Is there a way to have a service method which will return the method name for each calling method?

For example:

private void method1(){

   String thisMethodName = getMethodName(); //will return "method1"

}

private void method2(){

   String thisMethodName = getMethodName(); //will return "method2"

}

private void getMethodName(/*Any params?*/){

   //Is there an implementation for that? (In the same class or in some service class)

}




dimanche 6 février 2022

How do I know the field is private in golang?

Running this program will cause it to panic when I try to get the value of a private field via reflection.

How do I know the field is private and skip it?

The Golang version is 1.16.13.





How to override a method on a reified type [duplicate]

I would like to override a method on a reified type, but preserve all other methods. What is the simplest way to do that? For example:

I have:

(deftype Adapter []
 some.namespace/SomeProtocol
 (type-name-get [this] (:Adapter))
 ...)
(def adapter-instance (Adapter.))

And I want to get:

(def modified-adapter-instance
 (some-magic-fn adapter-instance type-name-get (fn [this] :ModifiedAdapter)))
(.type-name-get adapter-instance) => :Adapter
(.type-name-get modified-adapter-instance) => :ModifiedAdapter

The best solution that I've found is here. Is uses delegating-proxy macro to create a proxy from the object. Then you can use update-proxy to override methods.





samedi 5 février 2022

How to use std::chrono::duration in RTTR with Visual Studio >= 2019?

I am using RTTR for reflection and I'd like to use Chrono for certain types. However the following fails on >= Visual Studio 2019

  using microsecDouble = std::chrono::duration<double, std::micro>;
  auto microsecDoubleType = ::rttr::type::get<microsecDouble>();

with

  foo.cpp
c:\workspace\rttr\include\rttr/detail/type/type_data.h(331,1): error C2752: 'rttr::detail::template_type_trait<T>': more than one partial specialization matches the template argument list [c:\workspace\test\build\foo.vcxproj]
          with
          [
              T=non_ref_type
          ]
c:\workspace\rttr\include\rttr/detail/misc/template_type_trait_impl.h(135,1): message : could be 'rttr::detail::template_type_trait<T<Args...>>' [c:\workspace\test\build\foo.vcxproj]
c:\workspace\rttr\include\rttr/detail/misc/template_type_trait_impl.h(136,1): message : or       'rttr::detail::template_type_trait<T<Args...>>' [c:\workspace\test\build\foo.vcxproj]
c:\workspace\rttr\include\rttr/detail/misc/template_type_trait_impl.h(137,1): message : or       'rttr::detail::template_type_trait<T<Args...>>' [c:\workspace\test\build\foo.vcxproj]
c:\workspace\rttr\include\rttr/detail/misc/template_type_trait_impl.h(138,1): message : or       'rttr::detail::template_type_trait<T<Args...>>' [c:\workspace\test\build\foo.vcxproj]
c:\workspace\rttr\include\rttr/detail/type/type_impl.h(304): message : see reference to function template instantiation 'std::unique_ptr<rttr::detail::type_data,std::default_delete<rttr::detail::type_data>> rttr::detail::make_type_data<T>(void)' being compiled [c:\workspace\test\build\foo.vcxproj]
          with
          [
              T=non_ref_type
          ]
c:\workspace\rttr\include\rttr/detail/type/type_impl.h(371): message : see reference to function template instantiation 'rttr::type rttr::detail::create_or_get_type<non_ref_type>(void) noexcept' being compiled [c:\workspace\test\build\foo.vcxproj]
c:\workspace\rttr\include\rttr/detail/misc/template_type_trait_impl.h(44): message : see reference to function template instantiation 'rttr::type rttr::type::get<std::micro>(void) noexcept' being compiled [c:\workspace\test\build\foo.vcxproj]
c:\workspace\rttr\include\rttr/detail/misc/template_type_trait_impl.h(44): message : while compiling class template member function 'std::vector<rttr::type,std::allocator<rttr::type>> rttr::detail::template_type_trait<T>::get_template_arguments(void)' [c:\workspace\test\build\foo.vcxproj]
          with
          [
              T=non_ref_type
          ]
c:\workspace\rttr\include\rttr/detail/type/type_data.h(301): message : see reference to function template instantiation 'std::vector<rttr::type,std::allocator<rttr::type>> rttr::detail::template_type_trait<T>::get_template_arguments(void)' being compiled [c:\workspace\test\build\foo.vcxproj]
          with
          [
              T=non_ref_type
          ]
c:\workspace\rttr\include\rttr/detail/type/type_data.h(331): message : see reference to class template instantiation 'rttr::detail::template_type_trait<T>' being compiled [c:\workspace\test\build\foo.vcxproj]
          with
          [
              T=non_ref_type
          ]
c:\workspace\rttr\include\rttr/detail/type/type_impl.h(304): message : see reference to function template instantiation 'std::unique_ptr<rttr::detail::type_data,std::default_delete<rttr::detail::type_data>> rttr::detail::make_type_data<T>(void)' being compiled [c:\workspace\test\build\foo.vcxproj]
          with
          [
              T=non_ref_type
          ]
c:\workspace\rttr\include\rttr/detail/type/type_impl.h(371): message : see reference to function template instantiation 'rttr::type rttr::detail::create_or_get_type<non_ref_type>(void) noexcept' being compiled [c:\workspace\test\build\foo.vcxproj]
c:\workspace\test\foo.cpp(7): message : see reference to function template instantiation 'rttr::type rttr::type::get<microsecDouble>(void) noexcept' being compiled [c:\workspace\test\build\foo.vcxproj]

When compiling with VS 2017, or with Linux, everything is fine. Has anyone bumped into this or knows how to get around this?

Thanks,





Interact with multiple versions of an external jar file

JavaApplication1 wants to instantiate objects defined in the jar file of (fully trusted) JavaApplication2. Not normally a problem - add the external JavaApplication2 jar file to the build path of the JavaApplication1 project and then import the appropriate classes. Simples.

But imagine a scenario where JavaApplication1 needs to use multiple different historical versions of JavaApplication2 at the same time. e.g. Instantiate an instance of a JavaApplication2Object from version 1.5 of JavaApplication2.jar, and then, in the same thread, instantiate a separate instance of JavaApplication2Object from version 1.8 of JavaApplication2.jar.

In C#, I would use reflection to load and interact with the correct DLL. How does one do the same thing in Java in order to deal with the fact that the namespaces and class names are all identical across all versions of JavaApplication2?





Using Reflection to create an instance of logging service throws PlatformNotSupported Exception ... Activation attributes not supported error

I am trying to write a wrapper to abstract away logging frameworks. As part of the effort, I am trying to instantiate logging services from string names. When I try the below code to create an instance of one of the services it fails with the stated error. At the same time another service implementing the same interface and with a similar constructor works.

ILoggerService.cs

 public interface ILoggerService
 {
    void Log(string logLevel, string state, string eventId);
 }

NLogService

 public class NLogService : ILoggerService
    {
        private NLog.Logger _logger;
        private NLogNotifications _notifications;

        public NLogService(Func<LoggerConfiguration> notifiers)
        {
           _notifications = new NLogNotifications(notifiers);
            _logger = NLog.LogManager.GetCurrentClassLogger();
            
        }


        public void Log(string logLevel, string logMessage, string category)
        {
            _logger = NLog.LogManager.GetLogger(category);
            _logger.Log(GetLogLevel(logLevel), logMessage, category);
        }


        private NLog.LogLevel GetLogLevel(string levelName)
        {
            if (levelName == "Critical") levelName = "Fatal";
            return NLog.LogLevel.FromString(levelName);
        }
    }

Log4NetService

 public class Log4NetService : ILoggerService
    {
        private log4net.ILog _logger;
        private Log4NetNotifications _notifications;

        public Log4NetService(Func<LoggerConfiguration> config)
        {
            _logger = 
                log4net.LogManager.GetLogger(typeof(Log4NetService));
            BasicConfigurator.Configure();
            _notifications = new Log4NetNotifications(config);
        }
        void ILoggerService.Log(string logLevel, string logMessage, string category)
        {
            _logger = log4net.LogManager.GetLogger(category);
            _logger.Logger.Log(GetLogEvent(logLevel, logMessage, category));
        }

        private log4net.Core.LoggingEvent GetLogEvent(string logLevel, string logMessage, string category)
        {
            return new log4net.Core.LoggingEvent(new log4net.Core.LoggingEventData() { 
                Level = GetLogLevel(logLevel),
                Message = logMessage,
                LoggerName = category
            });
        }

        private Level GetLogLevel(string logLevel)
        {
            return _logger.Logger.Repository.LevelMap[logLevel];
        }
    }

The code that throws the exception looks like below -->


(_name, _getCurrentConfig, Logger) = (name, getCurrentConfig,
(ILoggerService?)Activator.CreateInstance(Type.GetType(lname)?.Assembly.FullName ?? "",
Type.GetType(lname)?.FullName ?? "", new [] { getCurrentConfig })?.Unwrap());
           




vendredi 4 février 2022

Can we use reflection to instantiate custom TypeScript model from a JSON string?

Is it possible to clone a JSON-generated object or string into a Typescript class which I created? We are building a model of our API using Typescript classes. There’s a base class which they all extend which has common/helper methods. When we do JSON.parse(response) to auto-generate objects it creates simple objects and not our custom objects.

Is there a way we can convert those JSON-generated objects into our custom objects, so long as the field names match up? And, to make things more robust, can this but done where our custom objects’ fields are other custom objects and/or arrays of them?

Here is our code, with comments of what we’d like to achieve.

base-model.ts

export class BaseModelObject {
    uuid: string; // All of our objects in our model and JSON have this required field populated
    matchUUIDs<T extends BaseModelObject>( obj: T): boolean {
        return obj.uuid == this.uuid;
    }
}

child-model.ts

import { BaseModelObject } from 'base-model';
export class Child extends BaseModelObject {
}

parent-model.ts

import { BaseModelObject } from 'base-model';
import { Child } from 'child-model';
export class Parent extends BaseModelObject {
  children: Child[];
}

JSON payload

{
    'uuid': '0632a35c-e7dd-40a8-b5f4-f571a8359c1a',
    'children': [
        {
            'uuid': 'd738c408-4ae9-430d-a64d-ba3f085175fc'
        },
        {
            'uuid': '44d56a0d-ad2d-4e85-b5d1-da4371fc0e5f'
        }
    ]
}

In our components and directives and such, we hope to use the helper function in BaseModelObject:

Component code

let parent: Parent = JSON.parse(response);
console.log(parent.uuid); // Works!  0632a35c-e7dd-40a8-b5f4-f571a8359c1a

// Want this to print ‘true’, but instead we get TypeError: parebt.matchUUID is not a function
console.log(parent.matchUUID(‘0632a35c-e7dd-40a8-b5f4-f571a8359c1a’));

// Want this to print ‘true’, but instead we get TypeError: parent.children[0].matchUUID is not a function
console.log(parent.children[0].matchUUID(‘d738c408-4ae9-430d-a64d-ba3f085175fc’));

The problem is that JSON.parse() is not creating our classes, it’s creating simple objects with key/value pairs. So we’re thinking of “cloning” the JSON-generated object into an instance of our class, like this:

base-model.ts

export class BaseModelObject {

    [key: string]: any;
    
    matchUUIDs<T extends BaseModelObject>( obj: T): boolean {
        return obj['uuid'] == this['uuid'];
    }

    cloneFields(obj: any) {
        for (let prop in obj) {
            this[prop] = obj[prop];
        }
    }
}

Component code

let parent: Parent = new Parent(); // Creates instance of our class
parent.cloneFields(JSON.parse(response)); // Copy JSON fields to our object
console.log(parent.matchUUID('0632a35c-e7dd-40a8-b5f4-f571a8359c1a')); // prints 'true'
console.log(parent.children[0].matchUUID('d738c408-4ae9-430d-a64d-ba3f085175fc')); // Still throws TypeError: parent.children[0].matchUUID is not a function

The problem now rests in the fact that the cloning of the Parent object did not recursively clone the JSON-generated Child objects into instances of our custom Child class.

Since our Parent object is typed at compile-time and it knows that the data type of the children array is Child[] (our custom class), is there a way to use reflection to instantiate the right class?

Our logic would need to say:

  1. Create an instance of our custom class
  2. Tell our instance to clone the fields from the JSON-generated object
  3. Iterate over the fields in the JSON-generated object
  4. For each field name from the JSON-generated object, find the "type definition" in our custom class
  5. If the type definition is not a primitive or native Typescript type, then instantiate a new instance of that "type" and then clone it's fields.

(and it would need to recursively traverse the whole JSON object structure to match up all other custom classes/objects we add to our model).

So something like:

cloneFields(obj: any) {
    for (let prop in obj) {
        let A: any = ...find the data type of prop...
        if(...A is a primitive type ...) {
            this[prop] = obj[prop];
        } else {
          // Yes, I know this code won't compile.
          // Just trying to illustrate how to instantiate
          let B: <T extends BaseModelUtil> = ...instantiate an instance of A...
          B.cloneFields(prop);
          A[prop] = B;
        }
    }
}

Is it possible to reflect a data type from a class variable definition and then instantiate it at runtime?

Or if I'm going down an ugly rabbit hole to which you know a different solution, I'd love to hear it. We simply want to build our custom objects from a JSON payload without needing to hand-code the same patterns over and over since we expect our model to grow into dozens of objects and hundreds of fields.

Thanks in advance! Michael





Clojure: override a method on a reified type

I would like to override a method on a reified type, but preserve all other methods. What is the simplest way to do that? For example:

I have:

(deftype Adapter []
 some.namespace/SomeProtocol
 (type-name-get [this] (:Adapter))
 ...)
(def adapter-instance (Adapter.))

And I want to get:

(def modified-adapter-instance
 (some-magic-fn adapter-instance type-name-get (fn [this] :ModifiedAdapter)))
(.type-name-get adapter-instance) => :Adapter
(.type-name-get modified-adapter-instance) => :ModifiedAdapter




jeudi 3 février 2022

Is there a good tutorial on using reflection and metaprogramming in Smalltalk?

In an advanced course on programming paradigms I want to confront students with the beauty and pitfalls of programming with reflection and metaprogramming. After having done this using the Ruby languages and before that with Java, I now want to return back to the more flexible Smalltalk language to illustrate these concepts in their purest form possible. To update my slides, is there any good tutorial, slide deck or any other documentation available which introduces reflection and metaprogramming in Smalltalk, preferably its Pharo dialect.

It should include concepts such as the class Object, the class Class, Smalltalk's meta-object protocol, specific hook methods such as methodDoesNotUnderstand, dynamic code compilation and modification, etc.





Set value of interface representing nil pointer using reflect in Go

My question is similar to How to initialize struct pointer via reflection.

I have an interface that represents a nil pointer. I want to update the value behind the nil pointer.

I took the code from one of the examples in the answers to the question mentioned above, but my situation is slightly different, and the given solution isn't working.

Inside InitNilPointer() the value actually does become &Foo{}. But the result at the call site remains (*Foo)(nil). How can I use reflect to update foo in main() to &Foo{}?

The situation is the following

func main() {
    var foo *Foo

    repository.InitNilPointer(foo)

    // Want: &main.Foo{A:""}
    fmt.Printf("Want: %+#v\n", &Foo{})

    // Got: (*main.Foo)(nil)
    fmt.Printf("Got: %+#v\n", foo)
}

// InitNilPointer initiates the given pointer to a nil value to become a pointer to 
// a value. E.g. (*Foo)(nil) becomes &Foo{}.
func InitNilPointer(source interface{}) {
    v := reflect.ValueOf(source)
    if reflect.Indirect(v).IsValid() {
        return
    }
    rv := reflect.ValueOf(&source).Elem()
    t := rv.Elem().Type().Elem()

    // This only updates the value locally. The call site still has a nil pointer. SAD.
    rv.Set(reflect.New(t))

    // source: &main.Foo{A:""}
    fmt.Printf("source: %+#v\n", source)
}




How to get enumerable or collection of values from WhereSelectListIterator

I need to write a generic method for getting distinct values and propertyName is not known in advance. I want to do it using the LINQ expression. I am trying the below way but when getting the result from SelectMethod invoke I am getting WhereSelectListIterator. I want to convert it to IEnumerable so I can call the Distinct method. But I am not to cast it to IEnumerable(as it's not implemented it). How to get Enumerable back from WhereSelectListIterator or is there any way I can get IEnumerable directly from invoke of generic method.

enter image description here





mercredi 2 février 2022

Dynamically create class instance with complex Class input parameters in Python using reflection

I am trying to make design metadata driven data pipelines, so I define in external textual metadata (json, yaml) things like:

dataFunctionSequence = DataFunctionSequence(
    functions=[
        Function(
            functionClass="Function1",
            functionPackage="pipelines.experiments.meta_driven.function_1",
            parameters=[
                Parameter(name="param1", dataType="str", value="this is my function str value")
            ]
        )
    ]
)

Now with help of importlib i can get class:

functionMainClass = getattr(
            importlib.import_module(

                functionMeta.functionPackage), functionMeta.functionClass)

But I want real instance, so I got it working with this piece of code which utilizes on top of importlib as well eval builtin function:

def create_instance(class_str:str):
    """
    Create a class instance from a full path to a class constructor
    :param class_str: module name plus '.' plus class name and optional parens with arguments for the class's
        __init__() method. For example, "a.b.ClassB.ClassB('World')"
    :return: an instance of the class specified.
    """
    try:
        if "(" in class_str:
            full_class_name, args = class_name = class_str.rsplit('(', 1)
            args = '(' + args
        else:
            full_class_name = class_str
            args = ()
        # Get the class object
        module_path, _, class_name = full_class_name.rpartition('.')
        mod = importlib.import_module(module_path)
        klazz = getattr(mod, class_name)
        # Alias the the class so its constructor can be called, see the following link.
        # See https://www.programiz.com/python-programming/methods/built-in/eval
        alias = class_name + "Alias"
        instance = eval(alias + args, { alias: klazz})
        return instance
    except (ImportError, AttributeError) as e:
        raise ImportError(class_str)

And I can construct a string that will construct the class and it works like charm.

Now my problem is that the class requires another parameter which is complex Spark DataFrame object which is not loaded from metadata but from some database or s3 bucket for example. Here I fail to be able to create dynamically instance with non-string variable.

I am failing here:

instance = eval(alias + args, { alias: klazz})

I tried to extend the create_instance() fnc with **kwargs, so I can dynamically search for parameter by name eg kwargs["dataFrame"], but how to assign it dynamically to init?

evel is not the right way probably or my expression is not correct?

NOTE: Another possible approach was to iterate somehoe over init object where I will get all params of constructor, but still I don't know what python reflection fuction to use to make a real instance.

Workaround: What I can do is that I can simply remove the dataFrame from class constructor, create instance only on simple params (eg. strings) and call method: instance.setDataFrame(dataFrame)

And it will work. but I wanted some reflection base approach if possible.

Thank you very much.

Ladislav





mardi 1 février 2022

How do I get all properties from an arbitrary Kotlin object?

This is another Kotlin oddity I've run into.

I had this code:

TableCharsets::class.declaredMemberProperties.asSequence()
    .map { p -> p.get(TableCharsets) }

and it worked fine.

Then I wanted to do it for more than one object in a loop. So I thought I could write this:

sequenceOf(TableCharsets, Iso2022Charsets, EucCharsets, ShiftJisCharsets).forEach { obj ->
    obj::class.declaredMemberProperties.asSequence()
        .map { p -> p.get(obj) }
}

But the compiler complains about the call to p.get(obj).

And indeed, if I write this:

val obj = TableCharsets
obj::class.declaredMemberProperties.asSequence()
    .map { p -> p.get(obj) }

This gives the same error. Apparently p.get(R) takes Nothing, so there is no possible object I can pass in which would be acceptable.

Thinking that maybe I lost the type of the object somehow, I tried extracting to a function so that it had a known but generic type:

fun <T: Any> extract(obj: T): Sequence<Any> {
    obj::class.declaredMemberProperties.asSequence()
        .map { p -> p.get(obj) }
}

Again, I get the error that p.get(R) only takes Nothing, and won't let me pass in a T.

When I hover over declaredMemberProperties, IDEA says that it returns a Collection<KProperty<T, *>>, but somehow the property p inside my lambda is a KProperty1<out Any, *>, so that's surely the problem. But it makes no sense to me right now how it is getting that type.

How can I make this work?





Improving code with reflection and generics

With the following code, how could I improve its readability using reflection and generics? It's a lot of repeated code, but I'm new to these concepts. "dl" is an interface but I'm not sure why I can't get access to the properties I want with .getType().getProperties(), it returns an empty list.

if (entity == "SERVICE")
{
    if (filter == "Active == 1")
    {
        foreach (var service in dl.Services.List().Where(x => x.Active).OrderBy(x => x.Name))
            tmpReturn.Add(service.ID, service.Name);

        return tmpReturn;
    }

    foreach (var service in dl.Services.List().OrderBy(x => x.Name))
        tmpReturn.Add(service.ID, service.Name);

    return tmpReturn;
}

if (entity == "CAMPAIGN")
{
    if (filter == "Active == 1")
    {
        foreach (var campaign in dl.Campaigns.List().Where(x => x.Active).OrderBy(x => x.Name))
            tmpReturn.Add(campaign.ID, campaign.Name);

        return tmpReturn;
    }

    foreach (var campaign in dl.Campaigns.List().OrderBy(x => x.Name))
        tmpReturn.Add(campaign.ID, campaign.Name);

    return tmpReturn;
}

if (entity == "AGENT")
{
    if (condition == "Active != ")
    { 
        if (value == "1")
        { 
            foreach (var agent in dl.Agents.List().OrderBy(x => x.Name))
                tmpReturn.Add(agent.ID, agent.Name);

            return tmpReturn;
        }

        foreach (var agent in dl.Agents.List().Where(x => x.Active).OrderBy(x => x.Name))
            tmpReturn.Add(agent.ID, agent.Name);

        return tmpReturn;
    }
    else if (condition == "Active == ")
    {
        if (value == "1")
        {
            foreach (var agent in dl.Agents.List().Where(x => x.Active).OrderBy(x => x.Name))
                tmpReturn.Add(agent.ID, agent.Name);

            return tmpReturn;
        }

        foreach (var agent in dl.Agents.List().OrderBy(x => x.Name))
            tmpReturn.Add(agent.ID, agent.Name);

        return tmpReturn;
    }
}