dimanche 28 février 2021

Update property of baseclass from derived class

I need to update a property in a base class through various derived classes, from a parent class.

This is my working code I'm using in LinqPad that will demonstrate the issue better.

void Main()
{
    var setting = typeof(Setting);
    PropertyInfo[] props = setting.GetProperties();
    
    string basePathValue = @"C:\my\path";
    
    foreach (var prop in props)
    {
        if (prop.PropertyType.IsSubclassOf(typeof(MyBase)))
        {
            // ???
            // string fullyQualifiedName = prop.PropertyType.FullName + ", " + assemName;
            // var t = (MyBase)Type.GetType(fullyQualifiedName);  // this doesn't work
            // t.BasePath = basePathValue;

            Console.WriteLine($"Name: {prop.PropertyType}");
            /*
            
            returns:
            Name: Customer
            Name: Profile
            
            */
            
            // How do I update the 'BasePath' property of each class
            // that inherits from MyBase and return the new
            // Setting class with the updated values?
        }
    }
    
    /*
    The result I want is:
    
    var customer = setting.Customer;
    var customerBasePath = customer.BasePath;
    // customerBasePath == "C:\my\path"
    */
}

// You can define other methods, fields, classes and namespaces here
public abstract class MyBase
{
    public string BasePath { get; set; }
}

public class Customer : MyBase
{
    
}

public class Profile : MyBase
{
    
}

public class Product
{
    
}

public class Setting
{
    public Customer Customer { get; set; }
    public Profile Profile { get; set; }
    public Product Product { get; set; }
}

I need to update the BasePath property in both the Customer and Profile classes, and then get an instance of the Setting class with the BasePath property values set.

I think it needs to be done via Reflection because other class properties could be added to Setting in the future and I would need to have all the class property's BasePath properties set.

Any guidance is appreciated.





Get all KeyPaths for an Object

Is there a way in Swift 5 to iterate over all keypaths? I'm aware Mirror will give you string representations of the keys, but I can't use setValue as my objects are not inherited from NSObject and several values are not @objc compatible. I am attempting to do something like the below (pseudo coded):

func overwrite(source:T, overwrite:T) {
  for keypath in overwrite.allKeypaths() {
    source[keyPath: keyPath] = overwrite[keyPath: keyPath]
  }
}

The end goal here is to create first a shallow copy into an existing object and possibly expand that out to include a deep copy based on the value type.





vendredi 26 février 2021

How to Group Class Property Members

I have a class which has properties with have common feaure with reflection i want to group this members. I mean class in the below i would like to group A and B Members. Main purpose here is to extract excel within A and B section. So my question is there any attribute for example [GroupParameter("A")] or method to achieve this.

public class LogParameters
{
    
    public byte A1{ get; set; }
    public UInt32 A2{ get; set; }
    public UInt32 A3{ get; set; }
    public byte A4{ get; set; }
    public byte A5{ get; set; }
    
    public byte B1{ get; set; }
    public UInt32 B2{ get; set; }
    public UInt32 B3{ get; set; }
    public byte B4{ get; set; }
    public byte B5{ get; set; }
}

Thanks.





Why are Kotlin interfaces "not open"?

When I type

open interface I

the Kotlin compiler warns me that modifier 'open' is redundant for 'interface'. This makes complete sense.

However, the reflection library seems to contradict this:

interface I
println(I::class.isOpen) // prints 'false'

How does this make sense? The KDoc of isOpen is very brief:

true if this class is open.

What exactly is the definition of "open" in Kotlin? I thought it meant "open to the possibility of being sub-typed by classes outside this file".





Why doesn't SQLAlchemy reflect tables in non-public schema?

I have a PostgreSQL database, which has had all objects in public schema. Used SQLAlchemy to succesfully connect to it and reflect objects from it.

Now I needed to create a separate schema schema2 in the same database. I assigned to new user all rights in that schema, checked that I can connect from command line with psql and do things in it.

But SQLAlchemy doesn't see any tables in the schema, when I try to use the same method to reflect its tables -- despite trying various ways to specify schema!

This is what worked for initial connection to public schema:

from sqlalchemy.ext.automap import automap_base
from sqlalchemy import create_engine
from sqlalchemy import Table, Integer, String, Text,  Column, ForeignKey

Base=automap_base()
sql_conn='postgres://my_user@/foo'
engine=create_engine(sql_conn)

Base.prepare(engine, reflect=True)

Then I could use Base.classes.* for tables and I didn't need to create Table classes on my own.

Now, this same works for this new user for public schema as well.

But whenever I somehow try to pass the schema2 to reflect tables from schema2, I always get empty Base.classes.*

I tried all the solutions in SQLAlchemy support of Postgres Schemas but I don't get anything at all reflected!

I tried:

  • making user's default schema schema2 via SQL means: ALTER new_user SET search_path=schema2;

  • tried to pass schema in engine.connect via engine options

  • tried to set schema in MetaData and use that, as per SQLAlchemy docs:

Doing:

meta=MetaData(bind=engine,schema='schema2')
meta.reflect()

does work, as I can see all the tables correctly in meta.tables afterwards.

However, when I try to get Base.classes working as per SQLAlchemy automapper docs, the Base.classes don't get populated:

from sqlalchemy.ext.automap import automap_base
from sqlalchemy import create_engine
from sqlalchemy import Table, Integer, String, Text,  Column, ForeignKey, MetaData

sql_conn='postgres://new_user@/foo'
engine=create_engine(sql_conn)
meta=MetaData(bind=engine,schema='schema2') 
Base=automap_base(metadata=meta)
Base.prepare(engine, reflect=True)

Base.classes is empty...

I am now stumped. Any ideas?

PS. I am working on newest SQLAlchemy available (1.3) under pip for Python2.7, Ubuntu 18.04LTS.





EF6 get tables dynamicly

I am using Entity Framework 6 with database first. Trying to display information about each table (DbSet), including number of entries. Eventually, I want to display some (TOP 200) rows of any selected table from my DbContext. I tried to achieve that using reflection without hard-coded specific types.

using (MyDataEntities pd = new MyDataEntities())
{
    var metadata = ((IObjectContextAdapter)pd).ObjectContext.MetadataWorkspace;

    var tables = metadata.GetItemCollection(DataSpace.SSpace)
        .GetItems<EntityContainer>().Single().BaseEntitySets.OfType<EntitySet>()
        .Where(s => !s.MetadataProperties.Contains("Type")
        || s.MetadataProperties["Type"].ToString() == "Tables").ToList();

    // This is working.
    var set = pd.GetType().GetProperty("MyType1").GetValue(pd);
    var theSet = set as DbSet<MyType1>;

    if (theSet != null)
    {
        int count = theSet.Count();     // This is working.
        var rows = theSet.ToList();     // This is working.
    }
          
    foreach (var t in tables)
    {
        dynamic dbset = pd.GetType().GetProperty(t.Name).GetValue(pd);
        int count = dbset.Count();      // This is not working
        var rows = dbset.ToList();      // This is not working
    }
}

I am getting exceptions:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:''System.Data.Entity.DbSet<MyAppName.MyType1>' does not contain a definition for 'Count''

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:''System.Data.Entity.DbSet<MyAppName.MyType1>' does not contain a definition for 'ToList''

Is this even possible what I am trying?





Is Java Reflection breaks access modifiers? then what is the real use of using access modifiers

We can access private variables through java reflection API, then what is the use of having access modifiers and also help me to get better understanding of real usage of access modifiers(private, public, etc) in real time applications.





jeudi 25 février 2021

Null check for reflected property's value with Any() keyword

I have a List of Entity Framework DAL objects where I am using a query parameter string that can include commas. I am trying to get all objects from the DAL List that satisfy the values in the query parameter string.

I have the following Linq statement that yields what I am expecting:

dalList = dalList
   .Where(aa => queryParamString.Split(',')
      .Any((x => (aa.GetType().GetProperty(kvp.Key).GetValue(aa, null)).ToString().ToLower() == x.ToLower())))
   .ToList();

The above statement works fine if the list does not contain a null value for the reflected property.

How can I include a null check into this Linq statement to avoid the NullReferenceException on the first ToString() method call?

Edit: kvp.Key is a string representation to a database column





GWT: get class literal from String containing its name and path

I am working on a GWT project and I'd like to get the class literal (not the instance) from a string that contains its canonical name. I wish I could use the method Class.forname but unfortunately, as you know, this method is not available on JRE emulation. Thanks for your feedback.





How to get entity class properties names from dbContext by table name?

I have dbContext and table name. I would like to receive all properties names from class that represent that table. Important thing - properies names in class, cause in class some properies are corrected with Column attribute to make class consistent with db entity.

public class MyTable
{
    public int Id { get; set;}
    public string Desc { get; set;}
    [Column("DbProp")]
    public int ClassProp{ get; set;}
}

Desired output: ["Id", "Desc", "ClassProp"]

I can get all table fields names from context metadata, but don't know how to "connect" them with Column attribute.

public static IEnumerable<SelectListItem> GetTableColumns(DbContext context, string table)
{
    var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;

    var tableType = metadata.GetItemCollection(DataSpace.SSpace)
                            .GetItems<EntityContainer>()
                            .Single()
                            .BaseEntitySets.OfType<EntitySet>()
                            .FirstOrDefault(s => (!s.MetadataProperties.Contains("Type") || (s.MetadataProperties["Type"].ToString() == "Tables"))
                                                 && string.Equals(s.Table ?? s.Name, table, StringComparison.OrdinalIgnoreCase));

    return tableType?.ElementType.Properties.Select(f => new SelectListItem
    {
        Text = f.Name,
        Value = f.Name
    });
}




JsonConvert.DeserializeObject knowing class name (string)

I've a vb.net class that includes some serializable sub-classes

Public Class Model
    <Serializable>
    Public class foo
        Public Property id as Integer
        Public Property name as String
    End Class

    <Serializable>
    Public Class bar
        Public Property grading as Integer
        Public Property minWage as Decimal
        Public Property maxWage as Decimal
    End Class
End Class

Now I receive from a web service, an object (as json formated string) and its class name (as string) and I'd like to Deserialize it as my object.

I could do, as it is actually working, a

Imports Newtonsoft.Json
    
Public Shared Function Deserialize(ByVal Json As String, ByVal name As String) As Object
   
    Select Case name
        Case "foo"
            Return JsonConvert.DeserializeObject(of Model.foo)(Json)
        Case "bar"
            Return JsonConvert.DeserializeObject(of Model.bar)(Json)
    End Select
End Function

But as you can imagine, I've a ton of classes, not just 2, so I tried to use Reflection

Imports System.Reflection
Imports Newtonsoft.Json

Public Shared Function Deserialize(ByVal Json As String, ByVal name As String) As Object

    Dim assembly As Assembly = Assembly.GetAssembly(GetType(Model))
    Dim type As Type = assembly.[GetType]("Model." & name) ' Why is this always Nothing?
    Dim objInstance As Object = Activator.CreateInstance(type)
    '        objInstance = JsonConvert.DeserializeObject(Of ???)(Json)

    Return objInstance 
End Function

But on one hand the type variable is always Nothing, and on the other hand, I don't know what to put instead of the comment.

Can you please advise ?





How to get class package after obfuscation for use in reflection with Proguard on Android

Currently class names are not being obfuscated. I need to find obfuscated package of specific class for use in reflection. Any ideas?





I am attempting to use Reflection.FieldInfo.SetValue on a structure field to modify its value, but to no avail. Why? (Code in C# and VB provided.) [duplicate]

I'm attempting to use Reflection.FieldInfo.SetValue to modify a structure's integer field value. However, it doesn't get modified.

I realize, that SetValue expects an Object, but boxing the integer doesn't help either.

What is my mistake?

Here's ready to copy and paste code in C# (further below in VB as well):

using System;
using System.Reflection;

public static class Test
{
    public struct SStruct
    {
        public int Value;
    }

    public static void Main()
    {
        // Initialize a structure record.
        SStruct rStruct = new SStruct();
        rStruct.Value = 42;

        // Reading the Value field by name:
        Type tStruct = typeof(SStruct);
        FieldInfo fValue = tStruct.GetField("Value");
        object oValue = fValue.GetValue(rStruct);
        Console.WriteLine("Read Value Before Mod: {0}", oValue);

        // Attempting to modify the Value field:
        fValue.SetValue(rStruct, 21);
        oValue = fValue.GetValue(rStruct);
        Console.WriteLine("Read Value After Mod:  {0}", oValue);
        // It didn't change.

        // SetValue is expecting an object though. Box the struct.
        object oStruct = rStruct;
        fValue.SetValue(oStruct, 21);
        oValue = fValue.GetValue(rStruct);
        Console.WriteLine("Read After Boxing:     {0}", oValue);
        // It didn't change.

        Console.Read();
    }
}

Here VB:

Imports System
Imports System.Reflection

Module Test
    Public Structure SStruct
        Public Value As Integer
    End Structure

    Public Sub Main()
        'Initialize a structure record.
        Dim rStruct As New SStruct
        rStruct.Value = 42

        'Reading the Value field by name:
        Dim tStruct As Type = GetType(SStruct)
        Dim fValue As FieldInfo = tStruct.GetField("Value")
        Dim oValue As Object = fValue.GetValue(rStruct)
        Console.WriteLine("Read Value Before Mod: {0}", oValue)

        'Attempting to modify the Value field:
        fValue.SetValue(rStruct, 21)
        oValue = fValue.GetValue(rStruct)
        Console.WriteLine("Read Value After Mod:  {0}", oValue)
        'It didn't change.

        'SetValue is expecting an object though. Box the struct.
        Dim oStruct As Object = rStruct
        fValue.SetValue(oStruct, 21)
        oValue = fValue.GetValue(rStruct)
        Console.WriteLine("Read After Boxing:     {0}", oValue)
        'It didn't change.

        Console.Read()
    End Sub
End Module




mercredi 24 février 2021

Change property value

I have a list that I would like to search and then I want to change the variables that are of the DateTime type to the local time.

  public static T LocalTime<T>(T value, string locationTimeZone)
        {

            if(value.GetType().IsGenericType && value.GetType().GetGenericTypeDefinition() == typeof(List<>))
            {

                IList collection = (IList)value;
                foreach (var element in collection)
                {
                    PropertyInfo[] props =  element.GetType().GetProperties();
                    foreach (var property in props)
                    {
                        if (property.PropertyType == typeof(System.DateTime?))
                        {
                            var localTime = LocalTimeConvert("Alaskan Standard Time", DateTime.Now);
                            property.SetValue(property, localTime);
                        } 
                        else if (property.PropertyType == typeof(System.DateTime))
                        {
                            property.SetValue(property, ((System.DateTime)property.GetValue(property, null)).AddDays(10), null);
                        }
                    }
                }
            }
            return value;
        }

I'm struggling with a part where I want to change that value. How I can get an value and change value from PropertyInfo ?





C# Reflection - Use reflection to call a method [duplicate]

This method that downloads files is being flagged as a possible path traversel security flaw, I've tried a few things, but nothing solves, my last alternative is to use reflection to hide the type and the checkmarx scan no longer identifies how being a method that handles file download

I understand that I would have to use reflection in the ReadAllBytes method and maybe change the return

I'm having trouble implementing the Index code via reflection

public ActionResult Index(string fileName)
     {
          string rootPath = System.Configuration.ConfigurationManager.AppSettings.Get("FinalUploadFolder");
          byte[] fileBytes = System.IO.File.ReadAllBytes(string.Format(Path.Combine(rootPath, fileName.ToString())));
          return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName.ToString());
     }




Use reflection in .net standard referenced from .net framework

I made a library in .net standard 2.0. It's a library that uses a factory to create WebService objects that have common methods since the WebServices are different versions. I opted to use reflection to invoke the method. It works great in my unit tests. I ran into a problem when I tried to actually use the library in my .Net Framework 4.8 project. When you do that you get this exception:

PlatformNotSupportedException: This operation is not supported on .NET Standard as Reflection.Emit is not available.

It's thrown from the Invoke method.

        protected virtual async Task<TReturn> CallWebMethod<TReturn>(string methodName, params object[] paramaters) {
            MethodInfo info = WebServiceInstance.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance);            
            return await (Task<TReturn>)info.Invoke(WebServiceInstance, paramaters);            
        }

I've tried adding the Nuget package for System.Reflection.Emit to the library and .Net Framework project to see if that makes it happy. It doesn't.

I'm at a loss, is there any way to use a .Net Standard library that implements some reflection from a .Net Framework project?





mardi 23 février 2021

C# Reflectively call method without access to instantiated type

I am working on a code base that offers a command to a message handler to intercept messages of a certain type.

The register function looks like this:

RegHandler<T>(Func<T, IMessageMetaData, Task> handler) where T : IMessage

I am looking to add some common functionality in how messages are preprocessed by creating an abstract class that does catches the messages that are forwarded from this function to the registering function. The base class will implement it's own "RegHandler" that keeps track of type/func<IMessage, IMessageMetaData, Task>. Then it will implement a

Task MsgHandler(IMessage, IMessageMetaData)

function which I will register as the handler for all types of inheriting classes.

Classes can inherit from this and flag their message handlers with an attribute. I will reflectively iterate the instantiated child class to to find the methods with the specified attribute and

  1. Register the Type/Function with the base class function, "RegHandler"
  2. Register the base class handler with the client as the handler to intercept this message (client.Register(childClass.MsgHandler)

In this way, the client should direct every message that is registered by inheriting classes to base class handler "MsgHandler", MsgHandler will do it's preprocessing then call the method implemented by the inheriting class so that it can do what it needs to do.

The normal way a class would call the RegHandler method is like this:

public class ClassWithHandler
{
    public async Task MyMessageHandler(MyMessageType message, IMessageMetatData) : where MyMessageType : IMessage
    {

    }
}

ClassWithHandler cwh = new ClassWithHandler();
client.RegHandler(cwh.MyMessageHandler);

I have seen this answer: https://stackoverflow.com/a/2933227/4089216 which shows how to call the method when you have access to the object, but it also includes the object in the call itself (i.e. Func<ClassWithHandler, IMessage, IMessageMetaData, Task>).

My issue is that I cannot change the client's version of "RegHandler" since too many legacy components rely on it, nor add functionality to the class to keep track of the instantiated class that owns the handler in order to reflectively call the method like the above.

Therefore I need to convert a MethodInfo (having access to the instantiated object) into a Func<IMessage, IMessageMetaData, Task> instead of the above method that would give me Func<ClassWithHandler, IMessage, IMessageMetaData, Task>. Is there a way to get the reference in the format that the RegHandler requires using reflection?

Thanks for your time, please let me know if you need more info





Loading assembly from a file and calling GetExportedTypes

I had an application under .Net framework 4.5 that would open an assembly from a file and return the tyes in it as an array which I could then work with.

I need to update that application to .Net 5 and when I call GetTypes or GetExportedTypes on it it throws a FileNotFoundException. I know that the reason is that there is an embedded dependancy within that dll but I don't mind ignoring any types that would be contained in that. I just need the types in the base dll. Anyway I can't seem to find any way to retrieve the types without hitting this exception and scoured google for the new proper way to do this but to no avail.

Here's a simplified block of code that used to work in .Net framework.

    private bool CheckAssembly(FileInfo assemblyPath)
    {
        var asm = Assembly.LoadFrom(assemblyPath.FullName);

        var types = asm.GetExportedTypes();

        ...
    }




Find Lombok getter/setter via Java Reflection API

Is it possible to find/invoke a getter or setter generated by the Lombok library? Standard class.getMethod doesn't work.





Call single public function of a class without using its name

Is it possible to invoke the function of a class based on the fact that it is the only public one ? What I mean:

Something like:

double res = MyClass().myFunction(n);

becomes

double res = MyClass()[0](n);

Ideally I would have liked to call the function using a string with its name:

double res = MyClass().reflection("myFunction")(n);

But it seems not possible without wasting at least twice the ink to write the function name (function pointer and corresponding string in a map).





dimanche 21 février 2021

How to register multiple implementations with its own interface in ASP.NET Core using Reflection?

I'm new to the Dependency Injection in ASP.NET Core 3.1, and I'm trying to create Singleton instances of my Repository classes using Reflection, but I can't get it to work.

Currently, the BookService uses the BookRepository from the DI:

public class BookService : IService
{
    private readonly IBookRepository _bookRepository;

    public BookService(IBookRepository bookRepository)
    {
        _bookRepository = bookRepository;
    }

    public async Task<Book> GetById(string id)
    {
        var find = await _bookRepository.FindAsync(id);
        return find;
    }
}

It works because I added a singleton service to the container, with the following code (link to Microsoft Docs): services.AddSingleton<IBookRepository, BookRepository>();

I'm trying to achieve the same result using Reflection.

BookRepository

public class BookRepository : BaseRepository<Book>, IBookRepository
{
}

IBookRepository

public interface IBookRepository : IAsyncRepository<Book>
{
}

This is what I have so far:

// Get all classes implementing IAsyncRepository
var repositoryTypes = assembly.GetTypes().Where(x => !x.IsInterface && x.GetInterface(typeof(IAsyncRepository<>).Name) != null);
foreach (var repositoryType in repositoryTypes)
   // Adds a singleton service of BookRepository
   services.AddSingleton(repositoryType);

But as you can see, the code above is adding only the BookRepository, missing to reference the IBookRepository interface, so it's throwing the following error:

System.ArgumentException: 'Cannot instantiate implementation type 'IBookRepository' for service type 'IBookRepository'.'

Do you know how can I do that?





Get value of System.out.println from main method called via reflection

I'm calling the main method of a class via reflection. For example:

Object o = clasz.getDeclaredConstructor().newInstance();
Method method = clasz.getMethod("main", String[].class);
method.invoke(o, new String[1]);

The called code looks as:

public class Test {
    public static void main(String[] args) {
        System.out.println("This is a test");
    }
}

The reflection works fine and I can see the message in the console.

Is there a way to register something like a binding to the method invocation, for example a PrintWriter or a custom decorated Writer, so I can get the print value as a String?





Create an object of random class in kotlin

I learned java and python in high school and I became very comfortable with python. I have recently started to learn kotlin, mainly for fun (the keyword for defining a function is fun so it has to be a fun language, right), but I have a little problem.

Let's suppose I have a hierarchy of classes for Chess pieces:

abstract class Piece {
    ...
}

class Rook : Piece() {
    ...
}

class Bishop : Piece() {
    ...
}
.
.
.

I am taking input from the user to generate the board, so if the user types r, I need to create a Rook object, if he types b, I need to create a Bishop etc.

In python, I'd probably use a dictionary that maps the input string to the corresponding class, so I can create an object of the correct type:

class Piece:
    ...


class Rook(Piece):
    ...


class Bishop(Piece):
    ...
.
.
.


input_map = {
    'r': Rook,
    'b': Bishop,
    ...
}

s = input_map[input()]()  # use user input as key and create a piece of the correct type

I was really amazed by this pattern when I discovered it. In java, I had to use a switch case or a bunch of if else if to achieve the same result, which is not the end of the world, especially if I abstract it into a separate function, but it's not as nice as the python approach.

I want to do the same thing in kotlin, and I was wondering if there is a similar pattern for kotlin since it's a modern language like python (I know, I know, python isn't new, but I think it's very modern). I tried to look online, but it seems like I can't store a class (class, not an object) in a variable or a map like I can in python.

Am I wrong about it? Can I use a similar pattern in kotlin or do I have to fall back to the when statement (or expression)?

If I am not mistaken, a similar pattern could be achieved in java using reflection. I never got to learn reflection in java deeply, but I know it's a way to use classes dynamically, what I can do for free in python. I also heard that in java, reflection should be used as a last resort because it's inefficient and it's considered "black magic" if you understand my meaning. Does it mean that I need to use reflection to achieve that result in kotlin? And if so, is it recommended to use reflection in kotlin, and is it efficient?

I'd like to know how I can approach this problem, and I accept multiple answers and additional solutions I didn't come up with. Thanks in advance.





how replace ReflectionParameter::getClass() deprecation

I've been looking for help for a while, have two methods which work under php 7.4 but no under php 8, its because in php8 ReflectionParameter::getType() replace getClass(), but when i make the modification it doesn't work. how to update the code and make it work please ?

All code and additional information

the problematic code :

 public function register(string $id): self
    {
        $reflectionClass = new ReflectionClass($id);
        if ($reflectionClass->isInterface()) {
            $this->register($this->aliases[$id]);
            $this->definitions[$id] = &$this->definitions[$this->aliases[$id]];
            return $this;
        }
        $dependencies = [];
        if (null !== $reflectionClass->getConstructor()) {
            var_dump($reflectionClass->getConstructor());
            $dependencies = array_map(
                fn (ReflectionParameter $parameter) => $this->getDefinition($parameter->getClass()->getName()),
                array_filter(
                    $reflectionClass->getConstructor()->getParameters(),
                    fn (ReflectionParameter $parameter) => $parameter->getClass()
                )
            );
        }
        $aliases = array_filter($this->aliases, fn (string $alias) => $id === $alias);
        $this->definitions[$id] = new Definition($id, true, $aliases, $dependencies);
        return $this;
    }
 public function make(ContainerInterface $container): object
    {
        $constructor = $this->class->getConstructor();
        if (null === $constructor) {
            return $this->class->newInstance();
        }
        $parameters = $constructor->getParameters();
        return $this->class->newInstanceArgs(
            array_map(function (ReflectionParameter $param) use ($container) {
                if ($param->getClass() === null) {
                    return $container->getParameter($param->getName());
                }
                return $container->get($param->getClass()->getName());
            }, $parameters)
        );
    }




How to subscribe a void method with no parameters to a static event(Action) that is in different class at runtime using Reflection in C#

So far I have been able to add any method that matches this signature (Action<ILoginSession>)successfully in the IsLoginCallback(MethodInfo method) method. But I tried using var runtimeDelegate = (Action)method.CreateDelegate(typeof(Action), null); with a null because the class is static but I keep getting an error. Is it possible to subscribe a void method with no parameters at runtime to an static event Action with no parameters? I have found similar questions but they used an instance of a class to get the static event but in my case the class is also static so I can't the type for a proper reference. Any help is appreciated thanks!

    public static void AddLoginRuntimeCallbackMethods()
    {
        Assembly assembly = Assembly.GetExecutingAssembly();

        foreach (var type in assembly.GetTypes())
        {
            foreach (var method in type.GetMethods(BindingFlags.NonPublic |
                BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))
            {
                if (method.ReflectedType.IsSubclassOf(typeof(VivoxManager))) continue;

                if (Attribute.IsDefined(method, typeof(LoginCallbackAttribute), false))
                {
                    if (IsLoginCallback(method)) continue;
                }
            }
        }
    }

    public static bool IsLoginCallback(MethodInfo method)
    {
        var runtimeDelegate = (Action<ILoginSession>)method.CreateDelegate(typeof(Action<ILoginSession>), null);
        if(method.GetCustomAttribute<LoginCallbackAttribute>(false) != null)
        {
            switch (method.GetCustomAttribute<LoginCallbackAttribute>(false).action)
            {
                case LoginAction.LogginIn:
                    VivoxLogin.VivoxLoggingIn += runtimeDelegate;
                    return true;
                case LoginAction.LoggedIn:
                    VivoxLogin.VivoxLoggedIn += runtimeDelegate;
                    return true;
                case LoginAction.LoggingOut:
                    VivoxLogin.VivoxLoggingOut += runtimeDelegate;
                    return true;
                case LoginAction.LoggedOut:
                    VivoxLogin.VivoxLoggedOut += runtimeDelegate;
                    return true;
            }
        }
        return false;
    }




samedi 20 février 2021

from scratch dependency injection container get error in php8

I made a small dependency injection container, inspired from Symfony covered by unit testing which works perfectly under php 7 but when switching to php8 get an error regarding the testIfServiceWithInjectionfound test which tells:

1) Tests\Container\ContainerTest::testIfServiceWithInjectionIsFound
App\Container\NotFoundException: 

C:\wamp\www\lockpassword\app\Container\Container.php:108
C:\wamp\www\lockpassword\app\Container\Definition.php:101
C:\wamp\www\lockpassword\app\Container\Definition.php:98
C:\wamp\www\lockpassword\app\Container\Container.php:126
C:\wamp\www\lockpassword\tests\Container\ContainerTest.php:57

think it is related to the update of ReflectionParameter :: getClass () because there is only that I change from then php7, give you the compet code, I've been stuck on it for a week now:

update:

The problem concerns certainly the ReflectionParameter in method make and register but don't know how to do it, can you show me?


     class ContainerTest extends TestCase 
    {
      public function testIfSharedServiceIsFound()
      {
          $container = new Container();
          $response1 = $container->get(ResponseContext::class);
          $this->assertInstanceOf(ResponseContext::class, $response1);
          $response2 = $container->get(ResponseContext::class);
          $this->assertEquals(spl_object_id($response1), spl_object_id($response2));
      }
    
      public function testIfNoSharedServiceIsFound()
        {
            $container = new Container();
            $container->getDefinition(ResponseContext::class)->setShared(false);
            $response1 = $container->get(ResponseContext::class);
            $this->assertInstanceOf(ResponseContext::class, $response1);
            $response2 = $container->get(ResponseContext::class);
            $this->assertNotEquals(spl_object_id($response1), spl_object_id($response2));
        }
    
        public function testIfServiceWithInjectionIsFound()
        {
          $container = new Container();
          $bar = $container->get(Bar::class);
          $this->assertInstanceOf(Bar::class, $bar);
          $this->assertInstanceOf(Foo::class, $bar->foo);
        }
    
        public function testIfServiceWithParametersIsFound()
        {
            $container = new Container();
            $container
                ->addParameter("path", "path")
                ->addParameter("action", "action")
            ;
            $route = $container->get(Route::class);
            $this->assertInstanceOf(Route::class, $route);
        }
    
        public function testIfServiceAliasIsFound()
        {
            $container = new Container();
            $container->addAlias(RequestContextInterface::class, RequestContext::class);
            $request = $container->get(RequestContextInterface::class);
            $this->assertInstanceOf(RequestContextInterface::class, $request);
            $this->assertInstanceOf(RequestContext::class, $request);
        }
    
        public function testIfServiceParameterIsFound()
        {
            $container = new Container();
            $container->addParameter("key", "value");
            $this->assertEquals("value", $container->getParameter("key"));
        }
    
      public function testIfParameterNotFound()
      {
          $container = new Container();
          $this->expectException(NotFoundExceptionInterface::class);
          $container->getParameter("fail");
      }
    
      public function testIfClassNotFound()
      {
          $container = new Container();
          $this->expectException(NotFoundExceptionInterface::class);
          $container->get(Fail::class);
      }
    } 


    class Container implements ContainerInterface
    { 
        /**
         * @var array
         */
        private array $parameters = [];
    
        /**
         * @var Definition[]
         */
        private array $definitions = [];
    
        /**
         * @var array
         */
        private array $instances = [];
    
        /**
         * @var array
         */
        private array $aliases = [];
    
        /**
         * Retrieves the requested reflection class and registers it.
         * 
         * @param $id The service identifier.
         * @return $this This registered service.
         */
        public function register(string $id): self
        {
            $reflectionClass = new ReflectionClass($id);
            if ($reflectionClass->isInterface()) {
                $this->register($this->aliases[$id]);
                $this->definitions[$id] = &$this->definitions[$this->aliases[$id]];
                return $this;
            }
            $dependencies = [];
            if (null !== $reflectionClass->getConstructor()) {
                $dependencies = array_map(
                    fn (ReflectionParameter $parameter) => $this->getDefinition($parameter->getType()->getName()),
                    array_filter(
                        $reflectionClass->getConstructor()->getParameters(),
                        fn (ReflectionParameter $parameter) => $parameter->getType() && !$parameter->getType()->isBuiltin() 
                        ? new ReflectionClass($parameter->getType()->getName()) : null
                    )
                );
            }
            
            $aliases = array_filter($this->aliases, fn (string $alias) => $id === $alias);
            $this->definitions[$id] = new Definition($id, true, $aliases, $dependencies);
            var_dump($this);
            return $this;
        }
    
        /**
         * Definition instance to gets for this service.
         * 
         * @param $id The id of Definition instance.
         * @return Definition Returns the definition value.
         */ 
        public function getDefinition($id): Definition
        {
            if (!isset($this->definitions[$id])) {
                $this->register($id);
            }
            return $this->definitions[$id];
        }
    
        /**
         * Adds an parameter to pass to the service constructor method.
         * 
         * @param $id The parameter name.
         * @param $value The parameter value.
         * @return $this Returns this parameter.
         */
        public function addParameter($id, $value): self
        {
            $this->parameters[$id] = $value;
            return $this;
        }
        /**
         * Gets an parameter to pass to the service constructor method.
         * 
         * @param $id The parameter name.
         * @return array|bool|float|int|string|null Returns the parameter value.
         * @throws NotFoundException When the parameter does not exist.
         */
        public function getParameter($id)
        {
            if (!isset($this->parameters[$id])) {
                throw new NotFoundException();
            }
            return $this->parameters[$id];
        }
    
        /**
         * Gets a service.
         * 
         * @param string $id The service identifier.
         * @return mixed|object Returns the associated service.
         * @throws NotFoundException When the service does not exist.
         */
        public function get($id)
        {
            if (!$this->has($id)) {
                if (!class_exists($id) && !interface_exists($id)) {
                    throw new NotFoundException();
                }
                $instance = $this->getDefinition($id)->make($this);
                if (!$this->getDefinition($id)->isShared()) {
                    return $instance;
                }
                $this->instances[$id] = $instance;
            }
            return $this->instances[$id];
        }
    
        /**
         * Determine if the given service is defined.
         * 
         * @param string $id The service identifier.
         * @return bool Returns true if the service is defined, false otherwise.
         */
        public function has($id): bool
        {
            return isset($this->instances[$id]);
        }
    
        /**
         * Adds a specific alias for this service.
         * 
         * @param string $id The service identifier.
         * @param string $class The associated class name.
         * @return $this Returns this alias.
         */
        public function addAlias(string $id, string $class): self
        {
            $this->aliases[$id] = $class;
            return $this;
        }
    
    
    }


    class Definition
    {
        /**
         * @var string
         */
        private string $id;
    
        /**
         * @var bool
         */
        private bool $shared = true;
    
        /**
         * @var array
         */
        private array $aliases = [];
    
    
    
        /**
         * @var Definition[]
         */
        private array $dependencies = [];
    
        /**
         * @var ReflectionClass
         */
        private ReflectionClass $class;
    
        /**
         * Definition constructor.
         * 
         * @param string $id The service identifier.
         * @param bool $shared the shared service.
         * @param array $aliases this alias
         * @param array $dependencies
         */
        public function __construct(string $id, bool $shared = true, array $aliases = [], array $dependencies = [])
        {
            $this->id = $id;
            $this->shared = $shared;
            $this->aliases = $aliases;
            $this->dependencies = $dependencies;
            $this->class = new ReflectionClass($id);
        }
    
        /**
         * Sets if the service must be shared or not.
         * 
         * @param bool $shared True if the service is shared. False else.
         * @return self Returns the shared service.
         */
        public function setShared(bool $shared): self
        {
            $this->shared = $shared;
            return $this;
        }
    
        /**
         * Whether this service is shared. 
         * 
         * @return bool Returns true if the container is shared. False else.
         */
        public function isShared(): bool
        {
            return $this->shared;
        }
    
        /**
         * Creates a service.
         *  
         * @param ContainerInterface $container Interface ContainerInterface allows to use it's methods
         * @return object Returns a new instance for the current service.
         */
        public function make(ContainerInterface $container): object
        {
            $constructor = $this->class->getConstructor();
            if (null === $constructor) {
                return $this->class->newInstance();
            }
            $parameters = $constructor->getParameters();
            return $this->class->newInstanceArgs(
                array_map(function (ReflectionParameter $param) use ($container) {
                    if ($param->getType() && !$param->getType()->isBuiltin() 
                    ? new ReflectionClass($param->getType()->getName()) : null === null) {
                        return $container->getParameter($param->getName());
                    }
                    return $container->get($param->getType()->getName());
                }, $parameters)
            );
        }
    
    }

interface ContainerInterface extends PsrContainerInterface
{
    /**
     * @param string $id
     * @return $this
     */
    public function register(string $id): self;

    /**
     * @param $id
     * @return Definition
     */
    public function getDefinition($id): Definition;

    /**
     * @param $id
     * @param $value
     * @return $this
     */
    public function addParameter($id, $value): self;

    /**
     * @param $id
     * @return mixed
     */
    public function getParameter($id);

    /**
     * @param string $id
     * @param string $class
     * @return $this
     */
    public function addAlias(string $id, string $class): self;
}




Does Unity supports AppDomain?

I am writing a small Unity program, which can load a .NET assembly file to check its types, because the need to unload the assembly, so the AppDomain is used, the demo code as follows:

AppDomain appDomain = AppDomain.CreateDomain("test");
byte[] bytes = File.ReadAllBytes(dllPath);
var assembly = appDomain.Load(bytes);
var types = assembly.GetTypes();

When this program load another Assembly-CSharp.dll file, the types got are always those defined in current project, don't know how to fix it, any help is appreciated.





vendredi 19 février 2021

Custom mapping complex DTO to another simpler DTO Spring Boot

I would like to map my complexDto to my QuestionAndAnswerDto such that questionLabel is the name of the property ex. "property_one" and the answer is the value of the property.

I tried using Reflection API and other multiple things like flattening the JSON. At this point, I believe that my approach is wrong. Is there a way to handle this? I couldn't find anything on stackoverflow.

public class QuestionAndAnswerDto {

private String questionLabel;
private String answer;

}

public class ComplexDto {

private List<Object1> property_one;
private Object2 property_two;
private String property_three;

}

public class Object1 {

private String property_four;

}

public class Object2 {

private String property_five;

}





How replace ReflectionParameter::getClass() in php8

In php8 ReflectionParameter::getType() replace getClass().

documentation

First i would like to know what is the difference between $parameter->getClass()->getName() and $parameter->getClass() ?

Then this two lines for ReflectionParameter $param:

$param->getClass()->getName()
$param->getClass()

In php 8 they are replaced identically by :

$param->getType() && !$param->getType()->isBuiltin() 
? new ReflectionClass($param->getType()->getName())
: null;

or have any difference ? Can you explain to me I am not understood thank you :)





jeudi 18 février 2021

Android: Access non-sdk(manufacturer-supplied libraries) APIs via reflection in android >=11

Starting Android 11 the Reflection based non-sdk(Private) api calls are blocked. Android system checks the caller of the reflection method and if its non-system app it rejects with error as blocklist/blacklist. 

"Accessing hidden method Lcom/example/com;->getSomeMethod()Lcom/example/com; (blacklist, reflection, denied)"

More details in links below.

https://developer.android.com/guide/app-compatibility/restrictions-non-sdk-interfaces#results-of-keeping-non-sdk

https://www.xda-developers.com/android-11-harden-hidden-api-restriction-meta-reflection/

https://androidreverse.wordpress.com/2020/05/02/android-api-restriction-bypass-for-all-android-versions/

one way to bypass is as below. https://github.com/ChickenHook/RestrictionBypass

Queries:

"The hidden API blacklist only applies to non-whitelisted user applications. System applications, applications signed with the platform signature, and applications specified in a configuration file are all exempt from the blacklist"

1)All Above quote still hold good for Android 11? what are the ways OEMs can whitelist a app to use Reflection like before?

2)Is the manufacturer-supplied libraries treated as non-sdk libraries?

  1. How is the Reflection worked in android 10(Target 29) for the same manufacturer-supplied libraries even when META REFLECTION not used?

https://www.xda-developers.com/android-development-bypass-hidden-api-restrictions/

Thanks





Using log4net in dynamically loaded assemblies

I have an application that uses reflection to dynamically load a plugin assembly using a common interface. The plugin wants to be able to use the logging library, specifically log4net available in the application and it actually can do so using the logger defined in the app.config, however this only works if the log4net referenced in the plugin solution matches the one found at runtime. The thing is I don't want to worry about this when deploying the plugin to the application, I'd like the plugin to use any log4net version available, as long as ILog interface is the same.

Let's say I have log4net 2.0.8 in my application but the plugin has a reference to 2.0.12, those have same ILog interface but I get error since version 2.0.12 is not found at runtime.

Is there any reasonable way around this?





Best way to cache methods?

I have an application that is made with reflection as i made it to work for multiple versions. it uses many methods, so i wanted to know what is the best way to cache methods, there are more than 80 methods, and I am currently using something like this, but when there are a lot of methods this looks very meshy and in terms of readibility it looks very bad. I would like to know if there is a better way thanks!.

    HashMap<String, Method> methodHashMap = new HashMap<>();
    Class<?> userClass = Class.forName("org.minecraft.users.User");

    methodHashMap.put("getId", userClass.getMethod("getId"));
    methodHashMap.put("getName", userClass.getMethod("getName"));
    methodHashMap.put("getCoins", userClass.getMethod("getCoins"));
    ...
    etc




Mocking a class whose static initializer threw ExceptionInInitializerError

I have a scenario where I need to load classes from unknown sources and instantiate them for mocking - I don't need the code to run, but methods and properties must be in the resulting instance. I also need the class's name to remain unchanged, so its instance can be assigned to fields from that type of other already loaded classes. Sometimes a class instantiation fails due to an ExceptionInInitializerError, leaving the class in an invalid state which is impossible to recover. I do not know which class will fail beforehand.

Consider this:

class A {
    static {
        // Throws exception, resulting in 'A' changing to an error state
    }
}
    
class B {
    // In case 'A' could not be instantiated properly, I wish to mock
    // it so it can be assigned to this field
    private A someField;
}

The following is what I came up with:

  1. Create a subclass of the failing class using ByteBuddy - fails with NoClassDefFoundError, probably because the superclass is in an error state.
  2. Modify the class's static initializer and wrap it in try-catch statements while it is loaded using a ByteBuddy's agent - this seems rather complicated to accomplish in a portable manner.
  3. Load a class in a separate temporary class loader and identify the initialization failure; if an ExceptionInInitializerError has been thrown, redefine that class and remove its static initializer. This also appears very complex to achieve and results in various linkage and circularity errors.

Am I missing something? Is there a simpler way to achieve what I'm looking for?





Does OR-tools CP-SAT solver supports "reflection" methods such as x.Min() and x.Max()?

I'm porting my old (from 2010) OR-tools CP solver models to the CP-SAT solver (in Python3). There are quite a few differences between these systems, but most are quite easy to port to the CP-SAT solver.

However, one thing I haven't found in the CP-SAT solver documentation is the "reflection" methods that the old CP solver supports, such as getting lower/upper bounds of a decision variables. E.g.

  # Old CP solver code
  solver = pywrapcp.Solver("Name")
  x = solver.IntVar(0,10, "x") 

  # ....
  x_lb = x.Min()  # lower bound
  x_ub = x.Max()  # upper bound
  # ... 
 

One can then use these lower/upper bounds of the variable to implement other constraints. (Here's a CP solver implementing the cumulative constraint using Min and Max methods: http://hakank.org/or_tools/furniture_moving.py )

Does the CP-SAT solver supports these kind of reflection methods?





ReflectionParameter::getClass() deprecation

When I do a test with phpunit i get this error: Method ReflectionParameter::getClass() is deprecated, this is after the migration to php8. How to make it work again ?

documentation

the lines concerned :

$parameter->getClass()->getName()
$parameter->getClass()

Full code:

public function register(string $id): self
    {
        $reflectionClass = new ReflectionClass($id);
        if ($reflectionClass->isInterface()) {
            $this->register($this->aliases[$id]);
            $this->definitions[$id] = &$this->definitions[$this->aliases[$id]];
            return $this;
        }
        $dependencies = [];
        if (null !== $reflectionClass->getConstructor()) {
            var_dump($reflectionClass->getConstructor());
            $dependencies = array_map(
                fn (ReflectionParameter $parameter) => $this->getDefinition($parameter->getClass()->getName()),
                array_filter(
                    $reflectionClass->getConstructor()->getParameters(),
                    fn (ReflectionParameter $parameter) => $parameter->getClass()
                )
            );
        }
        $aliases = array_filter($this->aliases, fn (string $alias) => $id === $alias);
        $this->definitions[$id] = new Definition($id, true, $aliases, $dependencies);
        return $this;
    }
    public function make(ContainerInterface $container): object
    {
        $constructor = $this->class->getConstructor();
        if (null === $constructor) {
            return $this->class->newInstance();
        }
        $parameters = $constructor->getParameters();
        return $this->class->newInstanceArgs(
            array_map(function (ReflectionParameter $param) use ($container) {
                if ($param->getClass() === null) {
                    return $container->getParameter($param->getName());
                }
                return $container->get($param->getClass()->getName());
            }, $parameters)
        );
    }

I tried Something like :

$param->getType() 
$parameter->getType()->getName()
$parameter->getType()->name




How to call mock-like reflection api method in unit testing when non-existing method call is made by object?

I am using mockito 1.7.4. I use a custom API to verify intended behavior in my current service, I can see the codes via decompiling. I built my logic on top of this behaviour verification and I want to unit test it. The verification step (which as API based) is:

private static boolean verifySomeBehaviour(String verifierMethodName, VerifierClass vf){
    CustomObject custObj = someService.getCustomObject("objectName");
    Method mthd = custObj.getClass().getMethod(verifierMethodName,VerifierClass.class);
    return mthd.invoke(custObj,vf);
}

In my testing environment, I mocked the someService.getCustomObject("objectName") part and it shows up perfectly. However, because the mock object does not contain given verifier method it throws a NoSuchMethodException.

In order to solve this, I added a method object (like mocking the reflection api's Method):

    Method mthd = null;
    try {
        mthd = co.getClass().getMethod("getClass",null);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

Because the object has getClass method and requires no parameters it perfectly builds a method. After that I want to call above method (named mthd) instead of orijinal one and change the invocation result as I want(true or false):

Mockito.when(co.getClass().getMethod(verifierMethodName,VerifierClass.class)).thenReturn(mthd);
Mockito.when(mthd.invoke(co, vf)).thenReturn(true);

Afterall that, it still gives me NoSuchMethodException at Mockito.when(co.getClass().getMethod(verifierMethodName,VerifierClass.class)).thenReturn(mthd).

How can I resolve this problem?





Iterate through a class and get value from a KeyValuePair list with the propertyname

Hi what is the best way to iterate through a class and get an ID from a KeyValuePair list with the property name?

I have a class:

bar {
 foo1 {}
 foo2 {}
 foo3 {
   prop1 {
     name : foobar1,
     amount : 2
   },
   prop2 {
     name : foobar2,
     amount : 3
   },
   ...
 }
 foo4 {}
}

And I have a List<KeyValuePair<string, string>>() which contains:

  prob1, 12345
  prob2, 44939
  ....

No I should iterate through the bar class and foreach property (foo1, foo2, foo3) I should get the value in the this KeyValuePar with the key which is in that case prop1 or prop2.

So the result should be in the end like :

{
  id : 12345 // this is from prop1
  name : foobar1
  amount : 2
},
{
  id : 44939 // this is from prop2
  name : foobar2
  amount : 3
}
...

Is there a smart way to do it?

Thanks in advance...





mercredi 17 février 2021

Trying to use reflection to concatenate lists of objects

I have below class

public class HydronicEquipment
{
    public List<LibraryHydronicEquipment> Source { get; set; }
    public List<LibraryHydronicEquipment> Distribution { get; set; }
    public List<LibraryHydronicEquipment> Terminals { get; set; }
}

and then i have the below class for "libraryHydronicEquipment"

public class LibraryHydronicEquipment : IEquipmentRedundancy
{
    public string Name { get; set; }
    public RedundancyStatus RedundancyStatus { get; set; }
    public EquipmentRedundancy EquipmentRedundancy { get; set; }
 }

I am trying to concatenate the list of "LibraryHydronicEquipment" objects available from all three properties (i.e) from source, distribution and terminal and General concatenate method will looks like as this below

 var source = hydronicEquipment.Source;
 var distribution = hydronicEquipment.Distribution;
 var teriminals = hydronicEquipment.Terminals;
 Source.Concat(Distribution).Concat(Terminals)

I am trying to achieve the same using reflection and the code looks like as below

 foreach (var (systemName, hydronicEquipment) in hydronicSystemEquipment)
 {
     bool isFirstSystem = true;                   
     var equipmentList = new List<string> { "Source", "Distribution", "Terminals" };
     var redundancyequipmentList = GetRedundancyEquipment(hydronicEquipment, equipmentList);                                  
  }

and the method GetRedundancyEquipment is looks like below

private static IEnumerable<IEquipmentRedundancy> GetRedundancyEquipment(HydronicEquipment hydronicEquipment, List<string> equipmentList)
{
    IEnumerable<IEquipmentRedundancy> equipmentRedundancies = new List<IEquipmentRedundancy>();
    dynamic equipmentResults = null;
    foreach(var equipment in equipmentList)
    {
        var componentList = hydronicEquipment.GetType().GetProperty(equipment).GetValue(hydronicEquipment, null) as IEnumerable<IEquipmentRedundancy>;
       equipmentResults =  equipmentRedundancies.Concat(componentList);
    }
    return equipmentResults;
}

The problem here is even though i have Source is having list of objects and Distribution is having list of objects, the equipmentResults is giving only one object instead of list of concatenated objects.

I am trying to return the IEnumerable<IEquipmentRedundancy> at the end using reflection method but it seems not working with the above code.

Could any one please let me know how can i achieve this, Many thanks in advance.





How do I obtain a property descriptor inside of a class proxy handler using JavaScript/TypeScript

With a class proxy I would like to interrogate the property descriptor before performing a particular action; do one thing if it's an accessor, do something else if it's a method, and a third thing if it's a property. The problem though is that I don't think I'm looking at the correct owner of the feature:

type Constructor<T> = new (...args: any[]) => T

const handler: ProxyHandler<any> = {
    get(target, propertyKey, receiver) {
        const desc = Object.getOwnPropertyDescriptor(target, propertyKey)
        console.log(desc) // undefined

        return Reflect.get(target, propertyKey, receiver)
    }
}

function Adapted<U extends Constructor<any> = Constructor<any>>(Base: U = Object as any) {
    return class extends Base {
        constructor(...args: any[]) {
            super(...args)

            return new Proxy(this, handler)
        }
    }
}

class Foo extends Adapted() {
    method() { return "foo" }
}

new Foo().method() // "foo"

Do I have to walk the prototype chain until I find the correct owner? Is it something simpler?





Java reflection: constructor for primitive int causes: java.lang.NoSuchMethodException: int.

When I try to get the constructor to create an int it throws a: java.lang.NoSuchMethodException: int.<init>(int)

A very simplified version of what I'm trying to do is below:

Class myClass = int.class;
Constructor ctor = myClass.getConstructor(int.class);

I've tried the following as well:

Constructor ctor = myClass.getConstructor(Integer.TYPE);
Constructor ctor = myClass.getConstructor(Integer.class);

to end up with the same exception. What could be causing this?





How to get Type from antoher project of class of from class name string

I need to get type of TestClass from AnotherProject.GetClassType method but I get null

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
namespace TestProject.MyClasses.Test
{

        public class TestClass
        {
          public void Print()
          {
            Console.Write("Hello World");
          }
        }
}

but I get type = null

I try this one Type type = Type.GetType("TestProject.MyClasses.Test.TestClass, TestProject");





How to parse Java annotation in generic type?

I have annotation like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface NotNull {}

And have a class:

class Main{
   List<@NotNull String> list;
}

How should i parse this annotation using Reflection API?





PHP reflection: Is there an equivalent for ::class for a method of a class?

In PHP it is possible to get a full class name via class name resolution like this:

Example:

namespace Name\Space;
class ClassName {}

echo ClassName::class;

Output: Name\Space\ClassName

This is better then using a string Name\Space\ClassName directly in the code because code introspection especially in IDEs can find an error directly.

I wonder if there is something similar for methods of a class - this would be specifically useful for callback functions.

This is how you can basically can pass a callback:

$a = function($callback,$arg) { return $callback($arg); }

$a('getInfo',5);

Instead of passing a string here (which might change) I would prefer to do something like this:

$a(MyClass::class::getInfo,5);

With I "go to declaration" click in the IDE I could go directly to getInfo plus I see errors in case with method does not exist anymore. Is there a way to achieve what I want to do here?





mardi 16 février 2021

Is there a way to find arg values reliably from case class which is used as annotation?

I am working in Scala programming language. We are using annotations to apply some metadata on class fields

e.g.

Annotation class

case class Address(city: City, zip: Zip)  extends StaticAnnotation //City and Zip are Enumeration types

Class that uses annotation

case class Person
(
  @Address(City.LA, Zip.SomeZip)
  Field: String
)

Now I want to retrieve the value of city (which is LA) and zip (which is SomeZip) as a string, regardless of the order of the arguments.

what I have tried is this

val fields = typeOf[Person].typeSymbol.info.decls
      .find(d => d.isMethod && d.asMethod.isPrimaryConstructor)
      .get.typeSignature.paramLists.head
    
for(annotation <- field.annotations){
    println(annotation.toString) //returns Address(City.LA, Zip.SomeZip)
}

the above code works and returns the string, which I can parse and retrieve the desired values as shown above. But it works only when the arguments are provided in true order -> (City, Zip) but not the other way around. e.g.

@Address(zip = Zip.SomeZip, city = City.LA) // returns Address(x$4, x$3)

How can i retrieve the correct values (enum strings if possible -> "LA", "SomeZip") for each arg?





Dynamically accessing nested fields from a pojo by field name

I am building functionality that is intended to support any arbitrary POJOs. I don't know the specifics of the POJO, I am just given it as input. I have to access certain fields from it, provided to me in string format, for example fieldA.nestedFieldB.nestedFieldC and I need to extract the value from the POJO.

How can I do this in a generic way? Is reflection the way to go? I thought about loading the POJO into a map and then accessing it that way but I think the conversion would be expensive and hope there is a better way.

Also there is no guarantee about what type the fields are.





lundi 15 février 2021

Why is a setter for public field private on certain devices?

I have a public field and I pass a reference to its setter to a method. Certain devices crash when accessing this setter.

Minimal example

var isDurationValid = false

fun onHoursSet(hours: Int) {
    evaluate(hours, ::isDurationValid.setter)
}

fun evaluate(hours: Int, setter: (Boolean) -> Unit) {
    setter.invoke(hours > 0 && hours < 24)
}

I have the following exception report on crash analytics on certain devices:

java.lang.IllegalAccessException: Class java.lang.Class<kotlin.reflect.jvm.internal.calls.CallerImpl$FieldSetter$BoundInstance> cannot access private field





Instantiating extended JNA Structure throws IllegalAccessException

I was having trouble getting com.sun.jna.Structure to work, so I tried copying the first JNA test I found and I can't even get that to work.

For convenience, try it online.


import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;

public class MyClass {
    public void testSimpleSize() throws Exception {
        class TestStructure extends Structure {
            public int field;
            @Override
            protected List<String> getFieldOrder() {
                return Arrays.asList("field");
            }
        }
        Structure s = new TestStructure();
        //assertEquals("Wrong size", 4, s.size());
    }

    public static void main(String[] args)
    {
        try
        {
            new MyClass().testSimpleSize();
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }
}

The code compiles ok, but when running I get

Exception in thread "main" java.lang.Error: Exception reading field 'field' in class MyClass$1TestStructure
    at com.sun.jna.Structure.getFieldValue(Structure.java:639)
    at com.sun.jna.Structure.deriveLayout(Structure.java:1285)
    at com.sun.jna.Structure.calculateSize(Structure.java:1159)
    at com.sun.jna.Structure.calculateSize(Structure.java:1111)
    at com.sun.jna.Structure.allocateMemory(Structure.java:414)
    at com.sun.jna.Structure.<init>(Structure.java:205)
    at com.sun.jna.Structure.<init>(Structure.java:193)
    at com.sun.jna.Structure.<init>(Structure.java:180)
    at com.sun.jna.Structure.<init>(Structure.java:172)
    at MyClass$1TestStructure.<init>(MyClass.java:8)
    at MyClass.testSimpleSize(MyClass.java:15)
    at MyClass.main(MyClass.java:23)
Caused by: java.lang.IllegalAccessException: class com.sun.jna.Structure cannot access a member of class MyClass$1TestStructure with modifiers "public"
    at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361)
    at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:591)
    at java.base/java.lang.reflect.Field.checkAccess(Field.java:1075)
    at java.base/java.lang.reflect.Field.get(Field.java:416)
    at com.sun.jna.Structure.getFieldValue(Structure.java:636)
    ... 11 more

Am I missing something?





classOf T instead of T$ for Java library that does reflection

I'm using Scala with a Java library that expects to be passed a class with a public static void main(java.lang.String[]) so it can run call it via reflection for integration tests.

object RestServer {
    def main(args: Array[String]): Unit = { /* run the server */ }
}

Due to the behavior described in this answer to another question, this gets compiled to two classes.

public final class com.example.RestServer$ {
  public static final com.optum.cql.rest.RestServer$ MODULE$;
  public static {};
  public void main(java.lang.String[]);
}

and

public final class com.example.RestServer {
  public static void main(java.lang.String[]);
}

When I pass the class to the library

@IntegrationTest(main = classOf[RestServer.type])
class MyTests extends RapidoidIntegrationTest { }

I'm actually passing the object singleton instance (RestServer$), not the RestServer class that has the static void main() method.

This wouldn't be a problem, except the library verifies that the method it is calling is both public and static before calling it?

How can I get the RestServer class instead?





How can I use Type.GetType() with List'1[UnityEngine.Vector3]?

I am currently using:

    public static Type FindType(string qualifiedTypeName)
    {
        Type t = Type.GetType(qualifiedTypeName);

        if (t != null)
        {
            return t;
        }
        else
        {
            foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                t = asm.GetType(qualifiedTypeName);
                if (t != null)
                    return t;
            }
            return null;
        }
      

kudos to @Alistar from this post : Type.GetType not working
However, even this doesnt work when it comes to a list of Vector3s from UnityEngine.
I know that you can include the relevant assembly also by adding ", UnityEngine" at the end, but it doesnt work.

Any ideas?





dimanche 14 février 2021

Check if interface{} is ptr to struct

I would like to check if a given f interface{} function argument is a pointer to a struct, but am struggling somehow:

Updated snippet:

package main

import (
    "fmt"
    "log"
    "reflect"
)

func main() {

    // Switch f between being a pointer or not
    f := &struct{Foo string}{"Bar"}

    if err := something(f); err != nil {
        log.Fatal(err.Error())
    }

}

func something(f interface{}) error {

    if reflect.ValueOf(f).Kind() != reflect.Struct  {
        return fmt.Errorf("not struct; is %s", reflect.ValueOf(f).Kind().String())
    }

    if reflect.ValueOf(f).Kind() != reflect.Ptr  {
        return fmt.Errorf("not ptr; is %s", reflect.ValueOf(f).Kind().String())
    }

    // Deal with element values...
    t := reflect.ValueOf(f).Elem()

    for i := 0; i < t.NumField(); i++ {
        fmt.Println(t.Type().String(), t.Field(i).Interface())
    }

    return nil
}

If f is passed to function as pointer i get a not struct; is ptr.

If f is passed to function as struct i get a not ptr; is struct.

Is there any way to make sure that the interface is a pointer to a struct? Seems like as soon as f is a pointer any further checks via reflection are not usable here. Many other solutions I found could get handled via type assertions but I just do not know what is coming in here. Basically it could be literally anything.

Sure I could just use the pointer check and leave everything else as a "developer error". I just thought I could handle it somehow.

Any ideas?





samedi 13 février 2021

Java: Adding an enum value on runtime

I have the following class.

package net.runelite.client.plugins;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter(AccessLevel.PUBLIC)
@AllArgsConstructor
public enum PluginType
{
    PVM("PvM"),
    PVP("PvP"),
    SKILLING("Skilling"),
    UTILITY("Utilities"),
    MISCELLANEOUS("Miscellaneous"),
    SYSTEM("System"),
    MINIGAME("Minigame"),
    GAMEMODE("Gamemode"),
    UNCATEGORIZED("Uncategorized");

    private final String name;

    @Override
    public String toString()
    {
        return getName();
    }
}

I need to add in an enum in the class above.

And in my use case i cannot modify the class itself so i need a way to inject/add one in there on runetime.

I was thinking of a method below, but did not find a working way to implent this.

try {
    Method valueOf = field.getType().getMethod("valueOf", String.class);
    Object value = valueOf.invoke(null, param);
    field.set(test, value);
} catch ( ReflectiveOperationException e) {

}




vendredi 12 février 2021

"Object does not match target" while trying to invoke method using Reflection [duplicate]

I am solving a problem where I need to iterate over bunch of DbSets and insert into them some data stored in Lists. I have decided that Reflection might be the best way, because otherwise there would be a lot of repetive code.

Type propType = _databaseContext.GetType().GetProperty(contextProp.Name)?.PropertyType;
MethodInfo methodInfo = propType.GetMethod("AddRange", new Type[] {values.GetType()});
methodInfo.Invoke(_databaseContext, new[] {values});

This peace of code throws exception which stays:

Object does not match target type.

I am using new Type[] {values.getType()} as a second parameter of GetMethod because otherwise it throwed exception saying Ambiguos match found.. I think it should assure that AddRange method accepts Lists as a parameters, but it doesn't.

Does anyone know where the problem might be?





Using Class class getMethod() & reflection to find the correct method based on parameter types (with possible upcast)

I'm playing around with Reflection and trying to dynamically call the best fit method based on method name and supplied arguments. I coded up a quick example. Given the method name and an acceptable parameter (or several parameters, eventually) can I identify the correct method to run?

As you can see in this example...

public class Methods
{
    public static void goober(Object o) {
        System.out.println("Object");
    }

    public static void goober(Double d) {
        System.out.println("Double");
    }

    public static void goober(double d) {
        System.out.println("double");
    }
}

import java.lang.reflect.Method;
public class MethodIDTester
{
    public static void main(String[] args) {
        Methods.goober(new Object());    //prints Object                
        Methods.goober(new Double(5.0)); //prints Double        
        Methods.goober(5.0);             //prints double        
        Methods.goober(5);               //prints double        
        Methods.goober(new Integer(5));  //prints Object   
        System.out.println();

        invoker("Methods", "goober", new Object());    //prints Object             
        invoker("Methods", "goober", new Double(5.0)); //prints Double
        invoker("Methods", "goober", 5.0);             //prints Double - Not what I wanted
        invoker("Methods", "goober", 5);               //prints NoSuchMethodException - Not what I wanted
        invoker("Methods", "goober", new Integer(5));  //prints NoSuchMethodException - Not what I wanted
    }

    public static void invoker(String cName, String mName, Object param) {
        try {
            Class<?> c = Class.forName(cName);        
            Method m = c.getMethod(mName, param.getClass());
            m.invoke(c, param);
        } catch (Exception e) { System.out.println(e); }
    }

}

How can I improve my invoker so that it connect the parameter to the correct method in the same way that java does when I call the method directly?

I'd want the parameter 5.0 to land in the method that receives a primitive double.

I'd want it to realize that the primitive int 5 can land in the method that receives a double.

I'd want it to realize that Integer object can land in the method that receives an Object object.

I'm hesitant to try to code my own system of upcasting because I don't necessarily know how java prioritizes the upcasts (especially when there are multiple parameters). I'd want to ensure that my system identifies the same method that the compiler would identify, and that seems dangerous. I'd rather just ask java which method it would use bind rather than trying to figure it out myself. Does anything like that exist?





Run function with known name from package with unknown name

I am creating a program that needs to access other packages functions, I know the function name because it will be standard for every package, what I don't know is the package name.

I would like to be able to include the package in the file but then have something like the following:

import github.com/user/unknownpackagename

...

packageName := "unknownpackagename"

// This is pseudo-code of course. Run is the function
// of which I know the name
(packageName).Run()

Is this in any way possible in Go?

[EDIT] Adding more info hoping to explain it better

I have developed a program that needs to run a function called "Run" from other packages.

I don't know how many packages will be added in the future as their name will be dynamically added to and retrieved from a database.

What I can do right now to solve the problem is the following:

import (
    github.com/user/unknownpackagename
    github.com/user/otherpackagename
)

...

packageName := getPackageName()

switch packageName {
case "unknownpackagename":
    unknownpackage.Run()
case "otherpackagename":
    otherpackagename.Run()
...
}

since there could be hundreds of different packages, I would like to avoid a big big switch statement replacing it with a simpler

"if the package name is this, execute Run() from this package"





Dynamically access property of property of struct

I have a large numbers of structs and all of them have responseId: String and there is a property with same name as the value of responseId that contains contactId: String.

  • responseId is always non-optional String.
  • contactId of inner object is also non-optional String
  • all inner objects are optional (at runtime only one of the objects will be non-nil)

Below are two examples:

protocol ContainerBase {
    var responseId: String { get }
}

struct Container1: ContainerBase {
    struct OtherA {
        let contactId: String
        let cats: [String] // Other info here, not related to OtherB
    }
    struct OtherB {
        let contactId: String
        let dogsNum: Int // Other info here, not related to OtherA
    }
    let responseId: String
    let otherA: OtherA? // Optional
    let otherB: OtherB? // Optional
}

struct Container2: ContainerBase {
    struct AnotherA {
        let contactId: String
        let passed: Bool  // Other info here, not related to AnotherB
    }
    struct AnotherB {
        let contactId: String
        let friend: String // Other info here, not related to AnotherA
    }
    let responseId: String
    let anotherA: AnotherA? // Optional
    let anotherB: AnotherB? // Optional
}

Question:

How can I access contactId from Container1 or Container2 dynamically? (I tried the non dynamic approach with an extra function for each ContainerN struct with a switch inside but this is getting crazy because I have too many this structs, I already made some typos and forgot some cases, caused bugs,... and I imagine the reliable solution is "reflexion"?).

Example:

For example, if responseId of Container1 is "otherA" then I should look for contactId inside of property otherA. Since I have several types of Containers with different types of unrelated inner objects each one, solution should not be specific to Container1 nor Container2 it should work with any ContainerBase.

I implemented a dirty code but it causes a warning and cannot find to work it without generating one. Also I think this does not work reliably (This is for my iOS app but this strangely this does not work in linux Swift). Is this even possible? or it is a compiler glitch?

let c1 = Container1(
    responseId: "otherA",
    otherA: Container1.OtherA(contactId: "123", cats: ["figaro"]),
    otherB: nil)

c1.findContactId() // expected "123"

Ugly code ahead:

extension ContainerBase {
    func findContactId() -> String? {
        let mirror = Mirror(reflecting: self)
        guard let tInnerRes = mirror.children.first(where: { $0.label == self.responseId })?.value else { return nil }

        // WARN: Conditional cast from 'Any' to 'Optional<Any>' always succeeds
        guard let maybeInnerRes = (tInnerRes as? Optional<Any>) else { return nil }

        guard let innerRes = maybeInnerRes else { return nil }
        let innerMirror = Mirror(reflecting: innerRes)
        let contactId = innerMirror.children.first(where: { $0.label == "contactId" })?.value as? String
        return contactId
    }
}

Any help is appreciated





Get struct Tag with reflection - Error: type reflect.Value has no field or method Tag

Let's say we have this PoC:

package main

import (
        "fmt"
        "reflect"
        "strings"
)

type MyStruct struct {
        Str string `gorm:"size:10" json:"string"`
}

func main() {
        aStruct := MyStruct{"Hello"}

        s := reflect.ValueOf(&aStruct).Elem()
        if s.Kind() == reflect.Struct {
                for i := 0; i < s.NumField(); i++ {
                        field := s.Field(i)
                        if field.IsValid() {
                                if field.CanSet() {
                                        fmt.Printf("%T\n", field)  // reflect.Value, need reflect.StructField
                                        gormTag := field.Tag.Get("gorm")  // Compile ERROR HERE
                                        gormSize := strings.Split(gormTag, "size:")[1]
                                        fmt.Println(gormSize)
                                }
                        }
                }
        }
}

The error is:

go run test1.go 
# command-line-arguments
./test1.go:22:22: field.Tag undefined (type reflect.Value has no field or method Tag)

Tested with go 1.14.6 and go 1.15.2.

In my understanding I need to cast (or get from) reflect.Value to reflect.StructField Any ideas how to do that?





jeudi 11 février 2021

Which usage is preferred Enum.values() or Enum.class.getEnumConstants()?

To get the array of enum constants of some Enum type TestEnum, we have two options - TestEnum.values() or TestEnum.class.getEnumConstants(). When I looked at the code, I could see that the getEnumConstants() is invoking the values() method through reflection and then caching it for future usage. Before returning, the array is cloned as well.

From the below question and its answers (which focuses only on performance), it seems that there aren't much difference in performance.

Comparison of enums values() method and class.getEnumConstants()

I would like to know whether one of these methods is preferred over the other. One scenario which I could think of is when creating a method which works on generics where we pass a generic enum class as the argument. In this case, we could only use the getEnumConstants approach.

Are there any other similar scenarios? If I am sure about the type of the enum which I am going to use, then isn't it better to use values() approach?





System.MissingMethodException Constructor on type xxx not found

I have a generic method, this method will receive a dbcontext type. This generic method should create a new instance from the received context type and return it.

a Dbcontext example:

  class SchoolContext:DbContext
    {

        public SchoolContext(DbContextOptions<SchoolContext> dbContextOptions):base(dbContextOptions)
        {
            
        }

        public DbSet<Branche> Branches { get; set; }
        public DbSet<Student> Students { get; set; }
    }

What i tried:

public static TContext GetInstance<TContext>(string connectionString) where TContext:DbContext
{
    var      optionsBuilder = new DbContextOptionsBuilder();
    optionsBuilder.UseSqlServer(connectionString);
    TContext context = Activator.CreateInstance(typeof(TContext), optionsBuilder.Options) as TContext;

    return context;
}

Erros I got :

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

so please how I can fix this issue ?





How to find all DateTime properties of anonymous object?

I want to convert all dates received from client into UTC before processing them in server side code. I am thinking to use ActionFilter where I want to find all the date fields from Request payload and convert those into UTC dates. I know Reflection helps in finding properties by it's type but it doesn't work in case of Anonymous objects.

Here is code example I am trying to follow





mercredi 10 février 2021

java.lang.ArrayStoreException in E2E Test caused by custom Constraint Annotation with Custom Validation Group

I'm writing an E2E Test for my REST-Application. So the test, that is located in the frontend, calls the deployed backend, this is working perfectly fine except for one tiny problem: When the readEntity Method on the received Response is called, an java.lang.ArrayStoreException occurs. My observations show that the Problem lies within a self written Constraint Annotation:

I've written my own Constraint-Annotation @Future for Bean-Validation, my POJO uses this Annotation to validate that a LocalDateTime is in the future. I've also provided two simple Interfaces, which are used as Validation-Groups:

public interface ExistingInstance extends Default {

}

and

public interface NewInstance extends Default {

}

When i use one of these Interfaces as a validation group in my custom Constraint Annotation like follows:

public class Book {

   @Future(groups=NewInstance.class)
   private LocalDateTime validFrom;

   private LocalDateTime validTo;

   // Getters & Setters...
}

I receive this Exception:

java.lang.ArrayStoreException
    at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:736)
    at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:543)
    at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:367)
    at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:298)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:132)
    at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:84)
    at java.lang.reflect.AccessibleObject.getAnnotationsFromCache(AccessibleObject.java:313)
    at java.lang.reflect.Field.declaredAnnotations(Field.java:1167)
    at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:1160)
    at com.fasterxml.jackson.databind.introspect.AnnotatedFieldCollector._findFields(AnnotatedFieldCollector.java:86)
    at com.fasterxml.jackson.databind.introspect.AnnotatedFieldCollector._findFields(AnnotatedFieldCollector.java:71)
    at com.fasterxml.jackson.databind.introspect.AnnotatedFieldCollector.collect(AnnotatedFieldCollector.java:48)
    at com.fasterxml.jackson.databind.introspect.AnnotatedFieldCollector.collectFields(AnnotatedFieldCollector.java:43)
    at com.fasterxml.jackson.databind.introspect.AnnotatedClass._fields(AnnotatedClass.java:371)
    at com.fasterxml.jackson.databind.introspect.AnnotatedClass.fields(AnnotatedClass.java:343)
    at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector._addFields(POJOPropertiesCollector.java:493)
    at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector.collectAll(POJOPropertiesCollector.java:421)
    at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector.getPropertyMap(POJOPropertiesCollector.java:386)
    at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector.getProperties(POJOPropertiesCollector.java:233)
    at com.fasterxml.jackson.databind.introspect.BasicBeanDescription._properties(BasicBeanDescription.java:164)
    at com.fasterxml.jackson.databind.introspect.BasicBeanDescription.findProperties(BasicBeanDescription.java:239)
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._findCreatorsFromProperties(BasicDeserializerFactory.java:328)
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._constructDefaultValueInstantiator(BasicDeserializerFactory.java:272)
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findValueInstantiator(BasicDeserializerFactory.java:223)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildBeanDeserializer(BeanDeserializerFactory.java:261)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:150)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:414)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
    at com.fasterxml.jackson.databind.DeserializationContext.findContextualValueDeserializer(DeserializationContext.java:558)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.createContextual(CollectionDeserializer.java:188)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.createContextual(CollectionDeserializer.java:28)
    at com.fasterxml.jackson.databind.DeserializationContext.handlePrimaryContextualization(DeserializationContext.java:765)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:535)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:293)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
    at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:591)
    at com.fasterxml.jackson.databind.ObjectReader._prefetchRootDeserializer(ObjectReader.java:2340)
    at com.fasterxml.jackson.databind.ObjectReader.forType(ObjectReader.java:723)
    at com.fasterxml.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:804)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:233)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:212)
    at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:132)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1072)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:885)
    at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:845)
    at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:340)
    at org.glassfish.jersey.client.InboundJaxrsResponse$2.call(InboundJaxrsResponse.java:104)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:205)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:365)
    at org.glassfish.jersey.client.InboundJaxrsResponse.runInScopeIfPossible(InboundJaxrsResponse.java:244)
    at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:101)
    at my.package.structure.books.BooksClient.readEntityFromResponse(BooksClient.java:309)
    at my.package.structure.books.BooksClient.getBooks(BooksClient.java:95)
    at my.package.structure.books.BooksClientTest.getBooks_Test(BooksClientTest.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:90)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
    at java.lang.reflect.Method.invoke(Method.java:508)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:436)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor$$Lambda$251.00000000126A8D40.execute(Unknown Source)
    at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:112)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$143.000000001120E090.execute(Unknown Source)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$146.000000001148A600.accept(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:195)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:186)
    at java.util.Iterator.forEachRemaining(Iterator.java:127)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1812)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:523)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:513)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:162)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:185)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:245)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:429)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$143.000000001120E090.execute(Unknown Source)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$146.000000001148A600.accept(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:195)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:186)
    at java.util.Iterator.forEachRemaining(Iterator.java:127)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1812)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:523)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:513)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:162)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:185)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:245)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:429)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$143.000000001120E090.execute(Unknown Source)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

Now the Confusing Part:

If i use my Validation-Group Interfaces on an Existing Annotation, provided by Java, like @NotNull:

public class Book {
   
   @NotNull(groups=NewInstance.class)
   private LocalDateTime validFrom;

   private LocalDateTime validTo;

   // Getters & Setters...
}

It works like perfectly fine. Even if i use a class provided in the JDK, like Default.class as a group on my Custom Annotation:

public class Book {
   
   @NotNull(groups=Default.class)
   private LocalDateTime validFrom;

   private LocalDateTime validTo;

   // Getters & Setters...
}

It works!

What am i missing?

I use:

  • Java v8
  • JavaEE v7
  • Jersey Client v2.33
  • Jersey HK2 v2.33

Note: I know that the Annotation `@Future` is already provided, but in Java 8 with JavaEE 7 it does not support the 'new' Time-API.