jeudi 31 décembre 2020

Reading Objects from another Process/JVM (JAVA)

What I have currently:

2 JVMs, and on 1 JVM I have an interchangeable array of objects (constantly re-ordering). For the ease of reading, I'm gonna refer to the first JVM which doesn't contain the array with JVM 1, and the second JVM with the interchangeable array with JVM2.

What I want : To reach an Object pulled out of the array at JVM2 on JVM1, by sending the object to shared memory (is it called native?) then JVM1 would grab the object from shared memory.

Why? JVM2 needs its garbage collection frequency unchanged and needs to stay light, therefore JVM1 has all the logic and load.

Problems/Constraints:

  • JVM2 array objects are Unserializable, and there is no way to serialize them due to them being not controlled by me (Fetched by Reflection).

  • JVM2 array is interchangeable and re-orders every Garbage Collection and gets added to all the time.

  • I need the object to have its direct reference intact, so it can't be copied or turned into XML for an example. so no XStream, No GSON.. etc..

  • I need to keep JVM2's garbage collection frequency the same, so I cannot increase load by much. (So basically, I can't just wrap the objects and store them in a map so that I can interact with the object's fields from JVM1)

  • JVM2's array and its contents are fetched by reflection as an "Object" type, so I can't physically just grab the array like this: "ClassContainingArray.getArray()".

  • Object sent by JVM2 to shared memory needs to be removed from memory once the same object at the array is garbage collected.

Example of what I want to do in code:

JVM2 (the one interchangeable array) class:

public class Main**JVM2** {

    public void getObjectFromArray() {
         Field field = classLoader.loadClass("ClassContainingArray").getDeclaredFields("array");
         Object[] arrayObject = (Object[]) field.get(null); //Static
         //... logic to get the wanted object from the array
         Object obFromArray = arrayObject[index_Fetched_from_logic_above];
         sendObjectToJVM1(obFromArray);
    }

    public void sendObjectTo**JVM1**(Object ob) {
        //Here I want to put the object into shared memory. But at the same time
        //I want it to be removed from shared memory once the same object from the array
        //has been garbage collected/removed.
    }

}

JVM1 class:

public class Main**JVM1** {

   public void receiveObject() {
        //Get the object from shared memory
        //Use reflection to get objects within (Primitive and Non-primitive)
        //If Getting objects-within isn't possible, it's alright at least I'll have a 
        //reference to the object which I can use to ask **JVM2** for the objects within.
   }
}

Note 1: The objects that will sent from JVM2 to JVM1 will be a lot (as there are lots of arrays and lots of objects (over-time of course).

Note 2: After sending the object to shared memory (it has to be removed once the same object in the array is removed/garbage collected)

Note 3: The object also have a connection by RMI for other stuff.

Questions you might have: (Will add more here, once asked in comments)

1) Where is the ClassContainingArray to the point you're getting it via Reflection? It's on another ClassLoader, as I'm attached to it (Java Attach API/Instrumentation).

-- Maybe there's something I can do with like ByteBuffer? Unsafe? I'm honestly lost in those 2.





Prevent reflection without SecurityManager

I'm making a java program inside an environment that loads code from files put in a "loading directory". This environment launches my code after it has already set an unreplacable SecurityManager. I'm trying to hide a SecretKey from any malicious code that can also be loaded in the same way as mine. It seems very hard if not impossible to hide a field from reflection without a security manager. The purpose of the code is to protect the end user from any malicious code that is put in the "loading directory".

Here is my code:

public class KeyStore {
    private static SecretKey key = null;

    public static SecretKey getKey() {
        if (!Utils.getCallerClassName(1).startsWith("my.package.and.ClassName")) throw new SecurityException("Not allowed to get security key!");
        return key;
    }

    public static void setKey(SecretKey key) {
        if (!Utils.getCallerClassName(1).startsWith("my.package.and.ClassName")) throw new SecurityException("Not allowed to set security key!");
        if (KeyStore.key == null)
            KeyStore.key = key;
    }
}

Where Utils.getCallerClassName() is:

    public static String getCallerClassName(int howFarBack) {
        StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
        if (stElements.length >= howFarBack + 3) return stElements[howFarBack + 2 /* One for getCallerClassName() and one for getStackTrace() */].getClassName();
        return stElements[stElements.length-1].getClassName();
    }

The loaded SecurityManager just prevents System.exit() and replacing it.

Is there any way to protect the key field from reflection? If not, what should I do to keep that data safe?





Checking for Method existence JUnit

I'm writing unit tests for a class A:

public class A {
   public void sayHello() {
      System.out.println("Hello!");
   }
}

I want to test method sayHello within A as follows:

public class Test {
   void test() {
      A a = new A();
      assertEquals(a.sayHello(), "Hello!");
   }
}

The issue is that sayHello might not exist in class A, which would cause this unit test to break. I want to prevent this behavior by failing the test prematurely if sayHello doesn't exist, which I tried to do by modifying test as:

public class Test {
   void test() {
      try {
         A a = new A();
         assertEquals(a.sayHello(), "Hello!");
      } catch (NoSuchMethodException e) {
          fail("sayHello doesn't exist);
      }
   }
}

This doesn't seem to work as the method doesn't compile! Is there a workaround to please the Java compiler? Note that I really want to keep a similar structure here by directly calling sayHello and I don't want to use call sayHello.invoke() because I already have a large codebase with code like this!





mercredi 30 décembre 2020

Why does Java not support accessing primitive return values when invoking methods without boxing via reflection?

I noticed that Java Reflection supports access on fields of primitive types such as boolean or int without boxing:

public final class Field extends AccessibleObject implements Member {
    //...
    public boolean getBoolean(Object obj) throws IllegalArgumentException, IllegalAccessException { ... }
    public char getChar(Object obj) throws IllegalArgumentException, IllegalAccessException { ... }
    public byte getByte(Object obj) throws IllegalArgumentException, IllegalAccessException { ... }
    public short getShort(Object obj) throws IllegalArgumentException, IllegalAccessException { ... }
    public int getInt(Object obj) throws IllegalArgumentException, IllegalAccessException { ... }
    public long getLong(Object obj) throws IllegalArgumentException, IllegalAccessException { ... }
    public float getFloat(Object obj) throws IllegalArgumentException, IllegalAccessException { ... }
    public double getDouble(Object obj) throws IllegalArgumentException, IllegalAccessException { ... }
    //...
}

However, there is only invoke(...) for methods which always returns Object. This forces boxing when it is used with methods with primitive return values. I wonder why there is no support for that yet. Has it not been asked for or are there serious issues which prevent it?





MethodInfo.GetParameters() throws System.IO.FileNotFound Exception

I am developing a project where I gather information from a previously created DLL file. I basically get structure of the DLL.

I use the following code to gather information.

public void Decode(string[] additionalFiles)
{
    Assembly assembly = Assembly.LoadFile(this.dllLocation);
    if(additionalFiles != null && additionalFiles.Length > 0)
        foreach (string af in additionalFiles)
        {
            Assembly additionalAssembly = Assembly.LoadFrom(af);
            AppDomain.CurrentDomain.Load(additionalAssembly.GetName());
        }
    Type[] types = assembly.GetTypes();
    Type[] public_classes = types.Where(x => x.IsPublic && !x.IsInterface).ToArray();
    foreach (Type type in public_classes)
    {
        if(type.IsClass)
        {
            MethodInfo[] class_methods = type.GetMethods().Where(x => x.Module.ScopeName != "CommonLanguageRuntimeLibrary").ToArray();
            for (int i = 0; i < class_methods.Length; i++)
            {
                try
                {
                    MethodInfo mi = class_methods[i];
                    ParameterInfo[] pars = mi.GetParameters();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
}

I get the assembly, classes, and methods. But when I try to get the parameters of a method I get System.IO.FileNotFound Exception. The code stops and opens OpenFileDialog. If I choose the same dialog again code restarts and gives the same Exception at the same point.

If I stop the code and try to see the properties of MethodInfo mi, I see the Exception is thrown.

Where I am doing wrong and what is the proper solution. I Googled it but it seems that I am playing by the book.

The Exception information I see is shown in the image enter image description here





How to check in C++ that identifier is declared?

I want to check at some point of code if some identifier x is declared, how do I do that?

I need this kind of check for different types of identifiers - variables, enum constants, functions, types, macros, etc. But for start I want to check at least variables and functions.

I need such kind of check (e.g. imaginary declared(x)) so that next code works e.g. for the case of int variable x:

if constexpr(declared(x)) {
    int y = x + 1;
} else {
    std::cout << "Variable 'x' not declared!" << std::endl;
}

For the case of macros of cause I can use #ifdef x, but how to do same check for variables/functions?

For the case of global non-lambda functions I figured out next code, based on overloaded functions resolution, but it needs using helper macros-based global definitions (can it be simplified more?):

Try it online!

#include <iostream>
#include <type_traits>

#define declared_func_helper(x, ...) \
    struct NotDeclared; \
    template <typename ... Args> \
    NotDeclared x(Args ...); \
    template <typename ... Args> \
    inline constexpr bool declared_func_##x(Args && ... args) { \
        return !std::is_same_v<decltype(x(args...)), NotDeclared>; \
    }

// declare some of functions
//void f(int a) {}
void g(bool b, char c) {}
    
// define helpers before or after declared functions
declared_func_helper(f);
declared_func_helper(g);

int main() {
    // check declaration of functions
    std::cout << "func 'f' declared: " << std::boolalpha << declared_func_f(int()) << std::endl;
    std::cout << "func 'g' declared: " << std::boolalpha << declared_func_g(bool(), char()) << std::endl;
}

which outputs:

func 'f' declared: false
func 'g' declared: true

For the case of non-global variables I implemented next code, but it also needs helpers definition through macroses:

Try it online!

#include <type_traits>
#include <iostream>

#define declared_var_helper(x) \
    struct NotDeclared_##x {}; \
    NotDeclared_##x x;
#define declared_var(x) \
    ([&](){ return !std::is_same_v<decltype(x), NotDeclared_##x>; }())
    
// use helpers before variables declaration
declared_var_helper(x);
declared_var_helper(y);

int main() {
    // declare some of variables
    //bool x = false;
    int y = 0;
    // ........
    // later check declaration
    constexpr bool is_declared_x = declared_var(x), is_declared_y = declared_var(y);
    std::cout << std::boolalpha << "var 'x' declared: " << is_declared_x << std::endl;
    std::cout << "var 'y' declared: " << is_declared_y << std::endl;
}

which outputs:

var 'x' declared: false
var 'y' declared: true

What about other cases, or easier ways to check?





mardi 29 décembre 2020

Using reflection to instantiate an IEnumerable

I've built a simple extensible computation framework, where each class represents a different function for the framework.

This is a quick example of what I did:

BaseFunction:

namespace MyNamespace
{
    public abstract class BaseFunction
    {
        public abstract string Name { get; }

        public abstract int Index { get; }

        public long Execute()
        {
            Execute(ReadInput() /* out of scope */, out long result);
            return result;
        }

        internal abstract void Execute(string input, out long rResult);
    }
}

SampleFunction:

namespace MyNamespace.Code
{
    public class SampleFunction: BaseFunction
    {
        public override string Name => "Sample Function";

        public override int Index => 1;

        internal override void Execute(string input, out long result)
        {
            result = 0;
        }
    }
}

Using reflection, the framework also provided a CLI where the user can select its function and run it.

This is how all the functions are retrieved:

public static IEnumerable<BaseFunction> Functions()
{
    return GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace.Code")
        .Where(type => type.Name != "BaseFunction")
        .Select(type => (BaseFunction)Activator.CreateInstance(type))
        .OrderBy(type => type.Index);
}

and this is how the CLI is built:

var menu = new EasyConsole.Menu();
foreach (var day in FunctionsUtils.Functions())
{
    menu.Add(function.Name, () => function.Execute());
}

The framework works fine, but, as you can see, everything is a long now, and this takes us to my issue: I'd like to make the BaseFunction class generic, so that I can have different functions returning different type of values.

However, changing BaseFunction to BaseFunction<TResult> breaks the Functions method as I can't return a IEnumerable<BaseFunction>.

The logical next step is to add an interface, make BaseFunction implement the interface and add the generics to BaseFunction. This means that Functions can now return a IEnumerable<IBaseFunction>.

What still doesn't work, however, is the way I build the CLI menu: my interface must have the Execute method, and so we're back to square one: I can't add that method to my interface, because the return type is a generic and the interface doesn't have the generic reference.

Here I'm kind of stuck.

Is there any way to make this kind of framework work without changing all my return types to object (or maybe struct?) considering that I may also need to return non-numeric types?





Workaround on casting Task

Background
I am trying to get a method (using reflection), and turn it to a delegate (using Delegate.CreateDelegate() method), and to boost the performance, cast the resulting Delegate object to a Func<Task<BaseClass>> so I can call Invoke() instead of DynamicInvoke() which is very slow.
However, I get an run-time error: Unable to cast ....

Simplified
Consider this scenario: Task<object> foo = (Task<string>)null;, where I want to cast Task<string> to Task<object> and it raises an error. Obviously because of the fact that Task<> is not contravariant.
If I wrap the Task<T> into another class (say Taskwrapper<out T>) and implement its implicit conversion, then Taskwrapper wouldn't be awaitable. Based on this issue on GitHub, I can now use ITask interface. But the code is not popular enough (or Microsoft-referenced) to rely on.
I'd like to know if any other way to cast Task<DeriveClass> to Task<BaseClass>? Or any alternative that keeps my method awaitable.

Some code

var genericTask = typeof(Task<>).MakeGenericType(dynamicOutputType);
var genericFunc = typeof(Func<>).MakeGenericType(genericTask);
var getResultDelegate = Delegate.CreateDelegate(genericFunc, result.ActionObject, "GetResult");
methodGetResult = (Func<Task<object>>)getResultDelegate; -- runtime Error here!

I want to cache the above methodGetResult variable and reuse it like this: cachedElements.MethodGetResult.Invoke(inputValue);





lundi 28 décembre 2020

How to create java.lang.reflect.Method using method stored in String

I want to parse method stored into string variable ex. "public void printStr(String arg) { System.out.println("Method called"); } " convert this into java.lang.reflect.Method object.





how to create a pointer to reflect.Value

I see many questions that appear to ask what I'm asking but I didn't see any actual response to the general question, just specific stuff.

I have reflect.Value of an int with a value of 64.

I have a slice that I got with reflection, that the type of the items in the slice is *int.

newSlice := reflect.Append(slice, currentRow.Convert(slice.Type().Elem()))
slice.Set(newSlice)

if I just run this, I get panic: reflect.Value.Convert: value of type int cannot be converted to type *int

I tried to run currentRow.Interface() but it returns an interface type pointer that cannot be added to the slice.

so how can I do that properly ?

I cannot know if it will be *int, or *string or anything else, I need it to be genneric





C# attributes and methods

Good day, everyone, recently I've come across the Discord.NET Api and was in love with the way Commands were handled. Essentially, to add a new Command that is executed when you write !ping, you can do this:

[Command("ping")]
public async Task Ping()
{
    //some logic here
}

And I really liked the easy nature of integrating new commands in an already existing API. So I wanted to recreate what was going on. In the beginning I was absolutely confused by the introduction of metaprogramming, but now feel a little more comfortable, so I tried to start, and designed an Attribute that was only assignable to methods:


[AttributeUsage(AttributeTargets.Method)]
    public class Command : Attribute
    {
        
        public string Name { get; set; }

        public Command(string name)
        {
            Name = name;
        }
        public Command()
        {
            Name = string.Empty;
        }
    }

Basic idea then is, that when my Console gets a command, I can run a method that has the command attribute and the name of what was entered in the console. So when I enter "ping" in the console, the below method is going to be executed.

[Command("ping")]
public void Ping()
{
    //do sth 
}

Now to the complicated part. How do I find and especially run that method? That's where I'm stuck right now. I really don't find anything helpful about that question on the .Net documentary or here on stackoverflow. Here is my attempt anyway:

public void Handle(string command)
{
    var methods = from t in Assembly.GetExecutingAssembly().GetTypes()
                  where t.GetCustomAttributes<Command>().Count() > 0
                  select t;
     //run method where command.name = ping
}

The idea behind that being, to iterate through all available methods in the assembly, and then putting those into a List of some kind and then executing the method that has the command.name of what was passed in as an argument to the Handle function. When I get that to work, I of course will initilaize the methods list in the constructor of that class and not everytime call it when Handle is called, but for simplicity in my question I formulated my question independent of that, to have my example minimal. The question now is, how do I iterate through all methods in my assembly, and save those with the command attribute into a collection, and how do I run a method that has a certain value for the command.Name property? I'am kind of new to that whole reflection stuff, so if I did something else stupid or you have general tips on that topic please let me know!! Thanks in advance!!





dimanche 27 décembre 2020

Can NET Framework 4.7.2 apps load at runtime NET Core 5.0 library DLLs?

I'm starting to port some of my NET Framework 4.7.2 class libraries to NET Core 5.0. The host Framework app dynamically discovers and runs Assembly.Load on the NET Core library ok. But when I try to do a Assembly.GetType(NET50Namespace.Classname) operation on the loaded assembly, it fails and returns null with the error:

{"Could not load file or assembly 'System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.":"System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"}

It looks like it is trying to load the NET Core 5.0.0.0 runtime, which I do have installed. I checked with the console command dotnet --list-runtimes and both the NETCore and WindowsDesktop runtimes are installed ok:

c> dotnet --list-runtimes

Microsoft.NETCore.App 5.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 5.0.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 3.1.5 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 3.1.10 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 5.0.0 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 5.0.1 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

I'm stuck.

Q1. Is it legal/possible for a Framework 4.7.2 app to dynamically load and run a NETCore 5.0 DLL? I was trying to port small pieces of my app to NET50 as a first step. But it is not working, and I might be trying to do the impossible.

Q2. If it is ok for Framework to load/call NET50 DLLs, what am I doing wrong, and how can I make the GetType call work so that I can instantiate and call the NET50 class library?

Thank you.





Mockito: Attach Answer to every method of arbitrary Object instance

I have the following situation:

I want to attach an Answer to every method call of a specific class instance. So for example with the class

public class Example {
    public int example1() { /* */ }
    public int example2(Object a) { /* */ }
    public int example3(Object a, Integer b) { /* */ }
    public int example4(int a) { /* */ }
}

I want to do the following

public Example attachToExample(Example ex) {
    Example spy = Mockito.spy(ex);
    Answer<Object> answer = /* */;
    doAnswer(answer).when(spy).example1();
    doAnswer(answer).when(spy).example2(any());
    doAnswer(answer).when(spy).example3(any(), any());
    doAnswer(answer).when(spy).example4(anyInt());
    return spy;
}

This works but what I would like to do is generalize this to not just Example instances but arbitrary Objects.

So what I would like to do is

public Object attachToExample(Object o) {
    Object spy = Mockito.spy(o);
    Answer<Object> answer = /* */;
    for(Method m : o.getClass().getMethods()) {
        /* skipping methods that cannot be mocked (equals/hashCode/final/..) */

        doAnswer(answer).when(spy)./* Method m with according arguments */;
    }
    return spy;
}

What I would need to do for that is construct argument matchers any/anyInt/.. depending on the amount of parameters of each method and their types (primitive/non primitive). Ideally I would create a list of arguments like this:

Class<?>[] params = m.getParameterTypes();
ArrayList<Object> args = new ArrayList<>();
for (Class<?> param : params) {
    if ("int".equals(param.toString())) {
        args.add(ArgumentMatchers.anyInt());
    } else { // Cases for other primitive types left out.
        args.add(ArgumentMatchers.any()); // Found non primitive. We can use 'any()'
    }
}
            
try {
    doAnswer(answer).when(spy).getClass().getMethod(m.getName(), m.getParameterTypes())
            .invoke(spy, args.toArray());
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    e.printStackTrace();
}

This does not work as using argument matchers outside of stubbing is not supported but I hope that this makes clear what I want to do.

Is there any way to make this work or is there a different way of archiving what I want to do?





samedi 26 décembre 2020

Are there any alternative ways to reuse RepresentationModelAssemblerSupport

With each Model class i have to create a RepresentationModelAssemblerSupport class, which is kind of redundant, so i write a generic RepresentationModelAssemblerSupport class.

Generic RepresentationModelAssemblerSupport class:

public class ModelAssembler<T, E extends RepresentationModel<E>> extends RepresentationModelAssemblerSupport<T, E> {
    private final Class<E> model;
    public ModelAssembler(Class<?> controllerClass, Class<E> resourceType) {
        super(controllerClass, resourceType);
        model = resourceType;
    }
    @Override
    protected E instantiateModel(T entity) {
        try {
            Constructor<E> constructor = model.getConstructor(entity.getClass());
            return constructor.newInstance(entity);
        } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
            throw new RuntimeException("lỗi server");
        }
    }

    @Override
    public E toModel(T entity) {
        Class<?> clazz = entity.getClass();
        try {
            Method method = clazz.getMethod("getId");
            Object id = method.invoke(entity);
            return createModelWithId(id, entity);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException("lỗi server");
        }
    }
}

It works but i have to use java reflection, which could lead to performance issues since toModel gets called every Request.

Are there any alternative ways to generalise RepresentationModelAssemblerSupport?

Here's an example of Model class:

@Relation(collectionRelation = "products", itemRelation = "product")
@Getter
public class ProductModel extends RepresentationModel<ProductModel> {
    private final UUID id;
    private final String name;
    private final Integer price;
    private final String description;
    public ProductModel(Product product) {
        this.id = product.getId();
        this.name = product.getName();
        this.price = product.getPrice();
        this.description = product.getDescription();
        add(linkTo(methodOn(ProductController.class).getProductColors(product.getId())).withRel("productColors"));
        add(linkTo(methodOn(ProductController.class).getProductTags(product.getId())).withRel("productTags"));
        add(linkTo(methodOn(ThumbnailController.class).getThumbnail(product.getThumbnail().getId())).withRel("thumbnail"));
        add(linkTo(methodOn(ProductController.class).all(0, new PagedResourcesAssembler<>(null, null))).withRel("all"));
    }
}




Python create instance of derived class

I want to have abstract class Task and some derived classes like TaskA, TaskB, ... I need static method in Task fetching all the tasks and returning list of them. But problem is that I have to fetch every task differently. I want Task to be universal so when I create new class for example TaskC it should work without changing class Task. Which design pattern should I use? Let's say every derived Task will have decorator with its unique id, I am looking for function that would find class by id and create instance of it. How to do it in python?





Java getMethods() with respect to inheritance hirarchy

What I eventually want to do is to invoke all methods that have some annotation in a way such that:

  1. Overridden methods will be invoked only once.

  2. In case the class of the object is B, and it inherits from A which inherits from Object, I want the methods defined in Object with that annotation to be invoked first, then the methods in A, and then the methods in B.

Is there a way to get the methods sorted in such way?





vendredi 25 décembre 2020

Reflection - How to copy common properties from one class to another when there are subclasses

I'm working on a c# application and trying to make this code working. It fails when it tries to copy a property which is a list of a subclass object. I'm able to check the common properties in both classes and the code works fine for most types I've used, even List<string>. When I have properties of type e.g. List<SubClass>it fails. The code fails also for simple objects of the Subclass.

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

namespace Questions
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 class1 = new Class1
            {
                Prop1 = "X",
                List1 = new List<Class1.SubClass>
                {
                    new Class1.SubClass { SubProp1 = "A", SubProp2 = "B" }
                }
            };

            Class2 class2 = class1.CopyTo<Class2>();    //---> fails when it tries to SetValue for the List<SubClass>
        }
    }

    public class Class1
    {
        public string Prop1 { get; set; }
        public List<SubClass> List1 { get; set; }

        public string Prop3 { get; set; }

        public class SubClass
        {
            public string SubProp1 { get; set; }
            public string SubProp2 { get; set; }
        }
    }

    public class Class2
    {
        public string Prop1 { get; set; }
        public List<SubClass> List1 { get; set; }

        public string Prop4 { get; set; }

        public class SubClass
        {
            public string SubProp1 { get; set; }
            public string SubProp2 { get; set; }
        }
    }

    public static class Extensions
    {
        public static T CopyTo<T>(this Object sourceObject) 
        {
            Type sourceObjectType = sourceObject.GetType();
            Type targetType = typeof(T);
            var targetInstance = Activator.CreateInstance(targetType, false);

            List<PropertyInfo> identicalProperties = new List<PropertyInfo>();

            var propertiesTarget = typeof(T).GetProperties();
            var propertiesSource = sourceObject.GetType().GetProperties();

            foreach (var s_property in propertiesSource)
            {
                foreach (var t_property in propertiesTarget)
                {
                    if (s_property.Name.Equals(t_property.Name))
                    {
                        identicalProperties.Add(s_property);
                        continue;
                    }
                }
            }

            object value;

            foreach (PropertyInfo property in propertiesTarget)
            {
                var res = identicalProperties.Any(x=>x.Name.Equals(property.Name));
                if (!res)
                {
                    continue;
                }
                value = sourceObjectType.GetProperty(property.Name).GetValue(sourceObject, null);
                property.SetValue(targetInstance, value, null);
            }

            return (T)targetInstance;
        }
    }
}

I assume this is achievable but I'm struggling to find a way to identify the type of property and when to cast the value to the correct type here property.SetValue(targetInstance, value, null);. value should probably be casted as a List. The error thrown by the compiler is: System.ArgumentException: 'Object of type 'System.Collections.Generic.List1[Questions.Class1+SubClass]' cannot be converted to type 'System.Collections.Generic.List1[Questions.Class2+SubClass]'

Can anyone help? Much appreciated.





MethodHandle cross ClassLoader method calls

The documentation of MethodHandles#Lookup says the following:

If the retrieved member is not public, smgr.checkMemberAccess(defc, Member.DECLARED) is called. (Note that defc might be the same as refc.) The default implementation of this security manager method inspects the stack to determine the original caller of the reflective request (such as findStatic), and performs additional permission checks if the class loader of defc differs from the class loader of the class from which the reflective request came.

So currently its not possible to invoke a method that has been loaded by a different ClassLoader. Is it possible to bypass this? Or should I just stick to normal reflection.





jeudi 24 décembre 2020

In scala how to determine whether a class object implements a trait

It is something as the code below. I found isAssignableFrom in Java but it's not in scala.

  trait A

  def isTraitA(c:Class[_]) = {
    // check if c implements A
    // something like 
    // classOf[A].isAssignableFrom(c) 
  }
  
  isTraitA(this.getClass)




What is the signature of a method with params?

I was about to bind Expression.Lambda programmatically (because of unknown/variable type parameters), and found out that if the target method uses params, the reflected calling is a bit different than calling directly.

First, in the official documentation, the "signature" (although this is more like a XML-doc):

public static
System.Linq.Expressions.Expression<TDelegate>
    Lambda<TDelegate>(
        System.Linq.Expressions.Expression body,
        params System.Linq.Expressions.ParameterExpression[]? parameters
    );

Notice that it the 2nd param is marked as optional, and we can write Expression.Lambda<T>(...). If in Visual Studio, you go to the disassembled declaration list, you can see this:

public static
Expression<TDelegate>
    Lambda<TDelegate>(
        Expression body,
        params ParameterExpression[] parameters
    );

2nd parameter is no longer marked as option. Now when I tried to invoke this method using reflection as:

    var lambdaFactory = typeof(Expression)
        .GetMethods()
        // Filter overloads
        .Single(x => x.ToString() == "System.Linq.Expressions.Expression`1[TDelegate] Lambda[TDelegate](System.Linq.Expressions.Expression, System.Linq.Expressions.ParameterExpression[])")
        .MakeGenericMethod(myTypeArgument);
    var lambda = (LambdaExpression) lambdaFactory.Invoke(
            null,
            new object[] {
                ...
                // ,null
            }
        );

, I got TargetParameterCountException: Parameter count mismatch.. But if null is added as another parameter, it works perfectly.

This is a bit strange for me. Why does the MS Docs use ? (optional marker)? Is the params argument really optional similarly to regualr option arguments, like string Foo(int a = 1); var result = Foo();? Or it is just a syntactic sugar? So that's why I may call directly Expression.Lambda<T>(...) in the editor, but the compiled code can be different (which is compatible with the reflection system too). If so, does that mean the method always receives the null value, even if I don't specify values? But if a method uses params argument, and nothing is passed, the argument from the method body is a valid array with .Count == 0, not null. Is it safe to pass null using reflection, or I should create an empty object array?





mercredi 23 décembre 2020

C# dynamically generate expression of property and empty argument

I need to create the following Lambda expression :

() => model.property

the model and its property will be determine at runtime. I want a function that takes the model and property and generate the expression:

public object GenerateLambda(object model, string property) 
{

}

If it is possible I don't want the function to be generic. but I think the main problem that I have is with () expression.





Instantiating a class by String name in Dart

I am trying to call a method of a class that I only know by name as a String. Now therefore I would need a ClassMirror of that class that allowes me to instantiate an instance. However, creating ClassMirrors seems to be only possible by entering a type using reflectClass(Type) or by passing an already existing instance of that class into reflect(dynamic). So these aren`t helping if I only have a String.

In Java you can do this pretty easily, by calling Class.forName(String). Then you would get a Constructor instance, make it accessibly and call it.

Does anyone know if this is even possible in dart? What seems weird is that once you have a ClassMirror you can access fields and methods by passing symbols, which can be created by Strings.





Is this reflection? Is there a better way to achieve modifying objects across difference classes?

I have an abstract class that creates a new instance of another class. In that class I create another object and need to modify that object based on the interfaces implementing class (abstract class's subclasses). I'm not sure if I'm waaaaaay overcomplicating this. And foremost would like to know if what I'm doing here considered reflection?

So for example:

interface MyInterface {
  modifySomeObject(SomeObject obj);
}

class AbstractClassA implements MyInterface {
  AbstractClassA() {
    SomeClassC c = new SomeClassC(this);
  }
}

class SomeClassC {
  SomeClassC(MyInterface interface) {
    SomeObject obj = new SomeObject();
    interface.modifySomeObject(obj);
  }
}

class SubclassX extends AbstractClassA implements MyInterface { 
  Override
  modifySomeObject(SomeObject obj) { 
    obj.doModificationX(); 
  } 
}

class SubclassY extends AbstractClassA implements MyInterface {
  Override 
  modifySomeObject(SomeObject obj) { 
    obj.doModificationY(); 
  } 
}




How to scan methods in all classes of a java application in runtime and call those methods according to the given request?

I want to implement REST api implementation for an old ERP system bounded to JAVA EE and JDK 1.8. It is not Spring. I want to create a servlet responsible for controlling requests with "/Rest/" path.

I want to find a suitable library for routing requests to classes. for example if a request comes with this URL : "BASEURL/Rest/com/humanresourse/apis/MCOMBPARTNER/save", the process should search in all jar files included in project in runtime and finds the package "com.humanresource.api" and in that finds the "MCOMBPARTNER" class and then calls the "save" method of it.

I don't want to use delegation or write a simple code I want to know best libraries that can help me doing this task in an enterprise way. Thanks





NullPointerException can't figure out

Recently I encounted a NullPointerException issue from a third party jar, still can't figure out how it happened after I dig into the code. Here is the error stacktraces

java.lang.NullPointerException
 at com.fasterxml.jackson.databind.introspect.AnnotatedCreatorCollector._findPotentialFactories(AnnotatedCreatorCollector.java:183)
 at com.fasterxml.jackson.databind.introspect.AnnotatedCreatorCollector.collect(AnnotatedCreatorCollector.java:57)
 at com.fasterxml.jackson.databind.introspect.AnnotatedCreatorCollector.collectCreators(AnnotatedCreatorCollector.java:47)
 at com.fasterxml.jackson.databind.introspect.AnnotatedClass._creators(AnnotatedClass.java:381)
 at com.fasterxml.jackson.databind.introspect.AnnotatedClass.getFactoryMethods(AnnotatedClass.java:293)
 at com.fasterxml.jackson.databind.introspect.BasicBeanDescription.getFactoryMethods(BasicBeanDescription.java:534)
 at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._addDeserializerFactoryMethods(BasicDeserializerFactory.java:852)
 at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._constructDefaultValueInstantiator(BasicDeserializerFactory.java:349)
 at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findValueInstantiator(BasicDeserializerFactory.java:269)
 at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.createCollectionDeserializer(BasicDeserializerFactory.java:1222)
 at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:399)
 at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
 at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)

it says the npe happen in line 183 of class AnnotatedCreatorCollector, here is the code and line num of AnnotatedCreatorCollector

177    private List<AnnotatedMethod> _findPotentialFactories(JavaType type, Class<?> primaryMixIn)
178    {
179        List<Method> candidates = null;
180
181        // First find all potentially relevant static methods
182        for (Method m : ClassUtil.getClassMethods(type.getRawClass())) {
183            if (!Modifier.isStatic(m.getModifiers())) {
184                continue;
185            }
186            // all factory methods are fine:
187            //int argCount = m.getParameterTypes().length;
188            if (candidates == null) {
189                candidates = new ArrayList<>();
190            }
191            candidates.add(m);
192        }

The only cercumstance I can imagine this npe will happen is the local variable 'm' is null, then I dig into the class ClassUtil and it goes

    public static Method[] getClassMethods(Class<?> cls)
    {
        try {
            return ClassUtil.getDeclaredMethods(cls);
        } catch (final NoClassDefFoundError ex) {
            // One of the methods had a class that was not found in the cls.getClassLoader.
            // Maybe the developer was nice and has a different class loader for this context.
            final ClassLoader loader = Thread.currentThread().getContextClassLoader();
            if (loader == null){
                // Nope... this is going to end poorly
                throw ex;
            }
            final Class<?> contextClass;
            try {
                contextClass = loader.loadClass(cls.getName());
            } catch (ClassNotFoundException e) {
                ex.addSuppressed(e);
                throw ex;
            }
            return contextClass.getDeclaredMethods(); // Cross fingers
        }
    }
    public static Method[] getDeclaredMethods(Class<?> cls) {
        return cls.getDeclaredMethods();
    }

I can see ClassUtil return an methods array using java reflection, but I think it's impossible that the array contain a null object, then I got stuck.

Here is my code

public class JsonUtil
{
...
  public static <T> T strToObj(String str, Class<T> clazz)
  {
    try
    {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(str, clazz);
    } catch (JsonParseException e) {
      e.printStackTrace();
    } catch (JsonMappingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
...
}




mardi 22 décembre 2020

Can I retrieve already parsed definition of function?

Using inspect.getsource you can retrieve definition / source code of a function in Python. Is there a way to retrieve that definition but as an already parsed object?

In other words, instead of a string, I'd like to get a list of some objects, each object represents one line of code and that object stores for example the function that is called at that line and all of the parameters of that function etc. So I'd expect that object to be a tree.

For example a line like that:

a = b(c, d(5))

would be a tree in which the root is "=" operator, below that is variable "a" and function "b", below function "b" is variable "c" and function "d", below function "d" would be literal 5.

In other words, I need to inspect the definition of a function, but with inspect.getsource, I would need to parse the returned string first so that I can work with that. Is there any way in which I can avoid doing that parsing and have it already parsed?





When is Mirror.Child label nil?

Documentation for Mirror.Child states,

When the label component in not nil, it may represent the name of a stored property or an active enum case. If you pass strings to the descendant(::) method, labels are used for lookup.

When is Mirror.Child label value nil?





NoSuchMethodException when trying to create ResponseSpecBuilder object

I'm trying to extend RequestSpecBuilder in Rest Assured and make it into a Singleton so I can front load things like the base uri and pass it around between Scenarios in a Serenity BDD implementation of Cucumber. The basic version (with everything else commented out, is this:

import io.restassured.builder.RequestSpecBuilder;

public class CareRequestSpecBuilder extends RequestSpecBuilder {

  private static CareRequestSpecBuilder builder;

  public CareRequestSpecBuilder() {
    super();
  }
}

I've tried it without super() as well. I've tried creating just a basic junit test in the library that creates the object and I still get the attempt to construct through Reflection and the NoSuchMethodException. That one is just a basic

import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.specification.ResponseSpecification;
import org.junit.Test;

public class DebugTest {

  @Test
  public void restAssuredTest() {
    ResponseSpecification resp = new ResponseSpecBuilder().expectStatusCode(200).build();
  }
}

The exception that comes from it is:

BUG! UNCAUGHT EXCEPTION: java.lang.invoke.MethodHandles$Lookup.<init>(java.lang.Class,int)
BUG! UNCAUGHT EXCEPTION: java.lang.invoke.MethodHandles$Lookup.<init>(java.lang.Class,int)
    at org.codehaus.groovy.vmplugin.v7.Java7.<clinit>(Java7.java:44)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
    at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:350)
    at java.base/java.lang.Class.newInstance(Class.java:645)
    at org.codehaus.groovy.vmplugin.VMPluginFactory.createPlugin(VMPluginFactory.java:56)
    at org.codehaus.groovy.vmplugin.VMPluginFactory.<clinit>(VMPluginFactory.java:37)
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.<init>(MetaClassRegistryImpl.java:99)
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.<init>(MetaClassRegistryImpl.java:71)
    at groovy.lang.GroovySystem.<clinit>(GroovySystem.java:33)
    at org.codehaus.groovy.runtime.InvokerHelper.<clinit>(InvokerHelper.java:61)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.createMap(ScriptBytecodeAdapter.java:621)
    at io.restassured.internal.ResponseParserRegistrar.<init>(ResponseParserRegistrar.groovy)
    at io.restassured.RestAssured.<clinit>(RestAssured.java:346)
    at io.restassured.builder.ResponseSpecBuilder.<init>(ResponseSpecBuilder.java:66)
    at <repo package>.autotest.DebugTest.restAssuredTest(DebugTest.java:11)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:119)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.lang.NoSuchMethodException: java.lang.invoke.MethodHandles$Lookup.<init>(java.lang.Class,int)
    at java.base/java.lang.Class.getConstructor0(Class.java:3508)
    at java.base/java.lang.Class.getDeclaredConstructor(Class.java:2711)
    at org.codehaus.groovy.vmplugin.v7.Java7.<clinit>(Java7.java:42)
    ... 65 more

The version if I let it go to the extend version is longer, but ultimately the same cause and process.

The constructor for RequestSpecBuilder is this:

private final ResponseSpecification spec;

public ResponseSpecBuilder() {
        spec = new ResponseSpecificationImpl(rootPath, null, getResponseParserRegistrar(), restAssuredConfig(), new LogRepository());
    }




How to inject code to a function that has an annotation in Flutter?

I would like to create several annotations for e.g. functions.

Every function that has that annotation I want to inject code to that function so that it fires additional code which is provided by annotation or some builder or...I don´t know how to realize that.

Any ideas?

Thanks for help!





KafkaConsumer generic types for avro SpecificRecord using Reflection

I want to initialize KafkaConsumer generic types using classes loaded with reflection. The classes will be generated via avro-tools and will be extending SpecificRecordBase class. I know, I can use wildcards and do something like -

KafkaConsumer<? extends SpecificRecordBase, ? extends SpecificRecordBase> consumer = new KafkaConsumer<>(properties);

However, I am looking for something like -

Class keyClass = Class.forName("com.test.KeyClass");
Class valueClass = Class.forName("com.test.ValueClass");
KafkaConsumer<keyClass, valueClass> consumer = new KafkaConsumer<>(properties);

Any pointers would be appreciated. Thanks.





Kotlin Reflection get parameter as String

I know that the title is probably misleading but I have no idea how to name it, so let me describe.

Lets take a simple assertion method

fun assertTrue(condition: Boolean) {
  Assert.assertTrue(condition)
}

Simple 'useless' wrapper. Then usage:

fun foo() {
  assertTrue((bool1 && bool2) || bool3)
}

Now in my assertTrue method I want to retrieve string like: "(bool1 && bool2) || bool3". I want to pass this to my logger so:

fun assertTrue(condition: Boolean) {
  logger.log("Condition [(bool1 && bool2) || bool3] == $condition")
  Assert.assertTrue(condition)
}

Is it possible to get this string via reflection or PsiManager?





How to listen to method invokation using Dart reflection?

i read a bit about dart mirrors but I did not figure out how to listen to method invocation using dart reflection.

Use Case:

Buttons in Flutter can have an onTap() method which is invoked when an user taps on that button.

I would like to listen to that invokation of onTap() using dart reflection to fire my own code when that happens...

how to realize that?





lundi 21 décembre 2020

Using reflection to verify all instances of a trait have a unique field

Consider the following code. Animals should have a unique ID. I want to dynamically verify (in a test) that all concrete subtypes of Animal have unique IDs. I want my test to fail if, for example, Cat and Fish both try to pass in uniqueId = 2.

sealed trait Animal {
  val uniqueId: Int
}

abstract class Mammal(val uniqueId: Int) extends Animal

abstract class Fish(val uniqueId: Int) extends Animal


case class Dog(age: Int, name: String) extends Mammal(1)

case class Cat(favouriteFood: String) extends Mammal(2)

case class Salmon(isCute: Boolean) extends Fish(3)

I'm using reflections to get the classes.

    import org.reflections.Reflections
    val reflections                 = new Reflections("package.blah")
    val allSubtypes: Seq[Class[_ <: Animal]] = reflections.getSubTypesOf(classOf[Animal]).asScala.toList
    val concreteSubtypes: Seq[Class[_ <: Animal]] = allSubtypes.filter(c => !Modifier.isAbstract(c.getModifiers))

I'm starting to suspect it might not be possible but would love to be wrong! I have the classes but no way to instantiate instances of them because all the constructors differ and I'm not sure if I can access the uniqueId from just the class.





dimanche 20 décembre 2020

How to call generic method by reflection using InvokeMember

I need to call a method via reflection. But the thing is that I don't want to find a method, I want to evaluate it at run-time using arguments. This is what I try to do:

class Program
{
    static void Main(string[] args)
    {
        var type = typeof(Test<int>);
        type.InvokeMember("Write", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
            null, new Test<int>(), new object[] {1, "1"});
        // The next call fails
        type.InvokeMember("Write", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
            null, new Test<int>(), new object[] { 2, 2 });
    }
}

public class Test<T>
{
    public void Write(T arg1, string arg2)
    {
        Console.Write(arg1);
        Console.Write(arg2);
        Console.WriteLine(" write1");
    }

    public void Write<T2>(T arg1, T2 arg2)
    {
        Console.Write(arg1);
        Console.Write(arg2);
        Console.WriteLine(" write2");
    }
}

The first call works fine but the second one generates an exception saying that Write() was not found. Can I call it using InvokeMember anyhow? I don't want trying to look for all methods and then call something like MakeGenericMethod()





Adjust return value of a method which is a singleton and has final access modifiers

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

public final class Foo {

    private static final INSTANCE = new Foo("Foo")

    private String name;

    protected Foo(String name) {
        this.name = name;
    }
    
    public final String getName() {
        return name;
    }

    public static Foo getInstance() {
        return INSTANCE;
    }
    
}

Some context:

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

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

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

Why do I need this?

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

Actual use case:

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

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





samedi 19 décembre 2020

Java Class to Encapsulate Large Number of Classes

I am fairly new to Java, though I've learned a lot thanks to OJT. I have a vexing problem in dealing with a legacy application's files. The application has over 600 record structures that must be handled in new Java programs being developed.

Systems vendor tools were used to generate Java classes for those 600+ structures, and those classes may get periodically re-generated due to unrelated changes. Those classes have getters/setters for the fields specific to that record, as well as marshall/unmarshall methods (for preparing a buffer for writing or processing a buffer after reading).

I've been asked to develop a "reader" class and a "writer" class to encapsulate the common functionality in those 600+ lower-level classes, and add additional processing, without writing 600+ individual "reader" and "writer" classes and replicating that additional code hundreds of times (and then having to maintain it).

I figured Java generics could help, and reflection could be used to invoke the marshall/unmarshal (and other common methods) in the specific, generated classes, but from within the generic class (if I said that right).

I've added all 600+ of those classes, and my attempts at a Reader class, in a library (jar) (throws & try/catch blocks removed for brevity):

public class RecordXyz {
    /* member data */

    /* misc other code */

    public byte[] marshal() { /*marhalling code*/ }
    public void unmarshal() { /*unmarhalling code*/ }
}

public class Reader<T> {
    private T       myT;
    private Method  getLength;
    private Method  unMarshall;

    Reader( T t, String fname ) {
        this.myT         = t;
        this.aClass      = (Class<T>)myT.getClass();
        this.marshall    = this.aClass.getMethod( "marshall", new Class[] { byte[].class, int.class } );
        this.unMarshall  = this.aClass.getMethod( "unmarshall", null );
    }
    /* Other member functions in Reader class */
}

Code trying to use the Reader class:

import io.RecordXyz;
import rw.Reader;

public class Test {
    public static void main( String[] args )
    {
        RecordXyz rec = new RecordXyz();

        */* compile error here */*
        testReader = new Reader<RecordXyz>( rec, "/usr/data/somefile.txt" );
    }
}

Unfortunately, I get a compile error on the instantiation of testReader: "The constructor Reader(T, String) is not visible"

Which makes no sense to me. But countless examples on this site and elsewhere say this is the way to do it. So, now I'm stumped and seek your help.

How do I to "pass" a RecordXyz object to the Reader class so it can use reflection to invoke the methods of a RecordXyz object at run-time? Is this even possible with Java?

I'm betting there's a simpler, more cogent solution. Please bear in mind that I'm limited to straight Java 1.8, though if there's an open source solution I may be able to convince management to approve its use.

Apologies for the verbosity but this is a stinker of a problem (for me anyway).

Thanks!





Calling a function from another namespace from a string C#

I know in C# you can call a function from a string by doing so

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

But I would like something like this

CallMethodFromName("Console.WriteLine", "Hello, world!");

How do I call a function from another namespace using reflection ?





Get fields in child class with reflection

I can't seem to find an answer to this question anywhere. It is probably because it is impossible but it is worth asking.

In my class, I have functions for discovering, loading and saving settings. These settings are declared using annotations. This class will be extended and the settings will be located in the child class. Is there a way to discover fields using reflection from the superclass without needing an abstract function in every implementation returning itself?





vendredi 18 décembre 2020

How to know if a struct's field is a pointer to struct or a struct or neither?

I'm using this code to scan each field of a struct.

var myModel *types.Struct
myModel, ok = pkg.Types.Scope().Lookup("customModel").Type().Underlying().(*types.Struct)
if !ok {
  panic()
}

for i := 0; i < myModel.NumFields(); i++ {
  if IsStruct(myModel.Field(i)) {
    println("How to do?")
  }
}

func IsPointer(field *types.Var) bool {
    _, ok := field.Type().Underlying().(*types.Pointer)
    return ok
  // THIS IS WORKING VERY WELL!
}

func IsStruct(*types.Var) {
  //HOW TO DO THIS?
  //I tried return reflect.TypeOf(field).Kind() == reflect.Struct but doesn't work!
}

I need to know if a field of my Struct is a Struct or not.

This field can be pointer or not.

Example:

type customModel struct {
  A string
  B *AnotherStruct
  C *AnotherOne
}

I tried return reflect.TypeOf(field).Kind() == reflect.Struct but doesn't.

IsPointer function as you can see it's working because I can use interface check.

How to do this with structs or *structs types?





C# Linq OrderBy Reflection with . deliminated string

I have a need to use a delimited string in order by. EG "Product.Reference".

I seem to be having trouble as the result is ordered the same way it was before the method was called.

For example I have this xUnit test that shows my issue. The asserts show that the order is still the same.

As you can see from the test I am using reflection in method private static object PathToProperty(object t, string path) So I am assuming I am doing something wrong in there?

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

namespace Pip17PFinanceApi.Tests.Workers
{
    public class InputViewModel
    {
        public List<OrderViewModel> OrderViewModels { get; set; }
    }

    public class OrderViewModel
    {
        public Product Product { get; set; }
        public decimal Price { get; set; }
    }

    public class Product
    {
        public string Description { get; set; }
        public string Reference { get; set; }
    }

    public class OrderByWithReflection
    {
        [Fact]
        public void OrderByTest()
        {
            //Arrrange
            var model = new InputViewModel
            {
                OrderViewModels = new List<OrderViewModel>
                    {
                        new OrderViewModel{
                            Product = new Product
                            {
                                Reference = "02"
                            }
                        },
                        new OrderViewModel{
                            Product = new Product
                            {
                                Reference = "03"
                            }
                        },
                        new OrderViewModel{
                            Product = new Product
                            {
                                Reference = "01"
                            }
                        },
                        new OrderViewModel{
                            Product = new Product
                            {
                                Reference = "04"
                            }
                        },
                    }
            };

            //Act
            var query = model.OrderViewModels.OrderBy(t => PathToProperty(t, "Product.Reference"));
            var result = query.ToList();

            //Assert
            Assert.Equal("01", result[0].Product.Reference);
            Assert.Equal("02", result[1].Product.Reference);
            Assert.Equal("03", result[2].Product.Reference);
            Assert.Equal("04", result[3].Product.Reference);
        }

        private static object PathToProperty(object t, string path)
        {
            Type currentType = t.GetType();
            foreach (string propertyName in path.Split('.'))
            {
                PropertyInfo property = currentType.GetProperty(propertyName);
                t = property;
                currentType = property.PropertyType;
            }
            return t;
        }
    }
}




jeudi 17 décembre 2020

How can I access and change a field value of object-member inside a object in kotlin by reflection?

For example, I want to access the property age using reflection from the Father object

data class Father(
   val children: Children()
)

data class Children(
   val age: Int
)




Java static initialisers when class not explicitly used

I've got a Java class that isn't explicitly referenced anywhere in my application - the intention is that it will be constructed by reflection. Is it expected that the static initialiser won't run if it's not referenced by any other class and no instance is explicitly constructed? That is:

class Test {   
    static { 
        System.out.println("static block"); 
    } 
} 
  
class Main { 
    public static void main(String args[]) { 
        /* The above print only seems to happen if you uncomment the next line */
        // new Test();

        /* Stuff that doesn't involve Test in any way */
        ...
        ...
    } 
}

won't hit that println?





Java: Does Java converts method arguments to array under the hood?

I'm trying to understand reflection and currently digging on how to call an instance method when you only have its name as string. For this reason invoke from java.lang.reflect.Method can be used. What bothers me is its signature invoke(Object obj, Object... args) where the first argument is an instance on which the method will be invoked and the second argument is just array of arguments for method invocation. In case of reflection passing arguments as array is the only option since invoke can invoke method with arbitrary num of arguments. What is really interesting to me is the same thing happens when you call the method directly(without reflection), are arguments also converted to array ? E.g. I have such method void foo(int x, String s, Bar bar) in my FooClass and if I call foo in regular manner new FooClass().foo(7, "HelloWorld", new Bar()) would Java under the hood convert all those three arguments to array as well, or array with argument is only used when you invoke method using reflection ?
Thank you





mercredi 16 décembre 2020

Blazor WebAssembly Reflection Missing System.Runtime

​I have started to work with Blazor and setup a hosted web-assembly application.

Within the App.Razor, I am using lazy loaded assemblies which are loaded from an API and then use Reflection to inspect each dll for an implementation of a specific interface.

This works perfectly fine when running the solution via Visual Studio (debugging). When I publish the solution, I am getting an error when loading the libraries stating System.Runtime 5.0.0.0 is missing.

This is working whenever it is being started in visual studio but not when running the published code.

I have tried this using Blazor server and this is working perfectly fine.

I have tried to work with adding false to see if the problem is caused by the linking but the issue still exists.

I have tried this on net5, net5.0.1 and net5 RC2.

Any advice would be much appreciated.

Thanks in advance​





Skipping properties that are read-only when setting using reflection

        public void ClickEdit(TItem clickedItem)
        {
            Crud = CrudEnum.Update;
            foreach (PropertyInfo prop in typeof(TItem).GetProperties())
            {
                prop.SetValue(EditItem, typeof(TItem).GetProperty(prop.Name).GetValue(clickedItem), null);
            }
        }

I created the above method to loop through an generic typed instance and use the value of that instance to set values in another instance of the same type.

However, some of the TItem properties are read-only, and then exceptions will be thrown.

What is the proper way to skip properties that are read-only and set only the properties that can be set?

Thanks!





How can I check whether `SomeType<>` implements `IEnumerable<>`?

I have an open generic type definition and want to check whether this open definition implements an open interface definition.

static bool IsOpenGenericTypeImplementing(this Type candidate, Type iface) => 
   candidate.IsGenericTypeDefinition && 
   candidate.GetGenericArguments().Length == 1 && 
   candidate.MakeGenericType(typeof(object)).IsAssignableTo(iface.MakeGenericType(typeof(object)));  // does not work

// example call will work:
var result = typeof(List<>).IsOpenGenericTypeImplementing(typeof(IEnumerable<>)); 

// following test will fail (exception)
class SomeType<T> where T : Enum, IEnumerable<T>
{
}

[Fact]
void CheckSomeType()
{
    Assert.True(typeof(SomeType<>).IsOpenGenericTypeImplementing(typeof(IEnumerable<>)));
}

The problem with the approach above is that is will fail if there are type constraints.

I found some similar questions but all seem to need a closed generic type definition (List<T>). E.g. Finding out if a type implements a generic interface





C# reflection, get ref return type from MethodInfo.Invoke

I use a static library class which has a static generic function, with where T : struct clause.

Also, this function returns ref T.

I wanted to use System.Type as parameter to invoke this generic function, so made a helper function which uses reflection.

public static object MyFunction(System.Type t, object[] params)
{
    var name = nameof(MyStaticLibraryClass.RefReturnStaticMethod);
    var method = typeof(MyStaticLibraryClass).GetMethod(name, BindingFlags.Public | BindingFlags.Static);
    var generic = method.MakeGenericMethod(someType);
    object ret = generic.Invoke(null, params);
    return ret;
}

Unfortunately when I use return value ret, it's value type rather than reference to that struct object.

While debugging, I found out that ret is marked as ByRef type of t.

So the question is, how do I use this object ret as ref type? Seems like return ref ret doesn't work...





mardi 15 décembre 2020

Hi I have the following test setup in which I am trying to check if a field exists, and set the value if it does.

In the step when it tries to set the value of the found field (i.e. field.set(cls, "Peter")), an exception is thrown

java.lang.IllegalArgumentException: Can not set java.lang.String field CustomerReservationReport.name to java.lang.Class

May I seek for you advice for the cause and resolution? Thank you.

Main logic:

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

public class Test {

    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException,
            InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException {
        Class<?> cls = Class.forName("CustomerReservationReportBasic");
        CustomerReservationReport customerReservationReport = (CustomerReservationReport) cls.getDeclaredConstructor()
                .newInstance();
        if (hasField(customerReservationReport, "name")) {
            Field field = cls.getSuperclass().getDeclaredField("name");
            field.setAccessible(true);
            field.set(cls, "Peter");
            System.out.println(customerReservationReport.getName());
        }
    }

    private static boolean hasField(Object object, String fieldName) {
        boolean isFoundInCurrentClass = Arrays.stream(object.getClass().getDeclaredFields())
                .anyMatch(f -> f.getName().equals(fieldName));
        boolean isFoundInParentClass = Arrays.stream(object.getClass().getSuperclass().getDeclaredFields())
                .anyMatch(f -> f.getName().equals(fieldName));
        return isFoundInCurrentClass || isFoundInParentClass;
    }
}

Models:

CustomerReservationReport

This is the parent class

import java.math.BigDecimal;

import lombok.Data;

@Data
public abstract class CustomerReservationReport implements Comparable<CustomerReservationReport> {

    private String name;
    private int num_of_visit;
    private BigDecimal total_spend;

    @Override
    public int compareTo(CustomerReservationReport customerReservationReport) {
        return this.getName().compareTo(customerReservationReport.getName());
    }
}

CustomerReservationReportBasic

This is the child class

public class CustomerReservationReportBasic extends CustomerReservationReport {
    public CustomerReservationReportBasic() {
        super();
    }
}




Decide if class has generic ancestor of specific generic argument type

Say I have a class CoolStorageClass, which inherits from StorageClassBase:

public abstract class StorageClassBase
{
//does something
}

public class CoolStorageClass : StorageClassBase
{
}

Then I have a generic abstract BaseClass<T> (which implements interface IBase<T>, which is probably not important for the question). It is important, that T can only be of type StorageClassBase.

public abstract class BaseClass<T> : IBase<T> where T : StorageClassBase
{
}

Then I have the implementation of the BaseClass with T as CoolStorageClass in the form of CoolClass:

public class CoolClass : BaseClass<CoolStorageClass>
{
}

I want to select all of my object, which are implementing the BaseClass<StorageClassBase> abstract class.

  1. does it make sense to check the generic of BaseClass? I mean, I could have classes, which inherit from BaseClass<DifferentStorageClassBase>...

  2. how do I check if a Type implements BaseClass<StorageClassBase>? I have found following [answer][1], but it does not check the type of the generic parameter. So I modified it into this:

    public static class TypeExtensions
    {
        //https://stackoverflow.com/a/457708
        public static bool HasBaseClassOf(this Type t, Type toCheck, Type genericParameter)
        {
            while ((t != null) && (t != typeof(object)))
            {
                var cur = t.IsGenericType ? t.GetGenericTypeDefinition() : t;
                if (toCheck == cur)
                {
                    //also check whether the generic types match
                    if (t.GenericTypeArguments[0].IsSubclassOf(genericParameter))
                    {
                        return true;
                    }
                }
                t = t.BaseType;
            }
    
            return false;
        }
    }
    

But this only checks for one generic type, and I don't understand why I have to check t.GenericTypeArguments instead of cur.GenericTypeArguments.

  1. What is the correct way to check for all the generic type arguments and the BaseClass?

  2. Currently I have to call the function like this: o.GetType().HasBaseClassOf(typeof(ProxyBase<>), typeof(ProxyDataPointBase)). How should I modify the function to be able to call it like this: o.GetType().HasBaseClassOf(typeof(ProxyBase<ProxyDataPointBase>))? [1]: https://stackoverflow.com/a/457708





Access variables from superclass while extending a library

I'm trying to access the variables of a superclass from a library. I'm currently using ImageListView, but I can't get the customization I need from the class ImageListViewItem. I looked at the source code from Github for ImageListViewItem, and I thought I would be able to extend the class and add another constructor like this:

 class CustomizableImageListViewItem : ImageListViewItem
{
    public CustomizableImageListViewItem(Image image, string fakePath, string name)
    {
        mZOrder = 0;
        Guid = Guid.NewGuid();
        ImageListView = null;
        

and there's about 15 more variables

This is part of the library I am trying to extend

public class ImageListViewItem : ICloneable
{
     #region Member Variables
     private int mZOrder;
     private string mText;
     private Guid mGuid;
     internal ImageListView mImageListView;

and like the previous example theres a lot more of these, I made sure to include the ones I was trying to use before

I get errors about how most of the variables don't exist in the current context. Why is this and is there any way to fix it?





How to get the name of a private field of a child class from the super class using Reflection or libraries?

Let's say I have this code structure:

public abstract class A {
 // members
 ...
 
 // constructor
 ...
 
 // methods
 protected void enterValue(By locator, String value) {
  ...
  System.out.println("entered " + value + " into the " + locator...);
 }
}

public class B extends A {
 // members
 private final By SEARCH_FIELD = By.id("search");
 // ... other FIELD members
 
 // constructor
 ...

 // methods
 public void searchProduct(String product) {
  enterValue(SEARCH_FIELD, product);
  ...
 }
}

The enterValue(By, String) method should prints for example: "entered Talent into the SEARCH_FIELD".
Also, I can have other classes of same structure as class B that can call class A method so I don't know the child class name and which field it would be in advance.
Is this something I can achieve with Reflection in Java or with some libraries?
My goal is to log every action with meaningful names into my ExtentReports.





Get From properties using reflection

I'm accessing form properties on this way:

System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetEntryAssembly();
Type[] Types = myAssembly.GetTypes();
foreach (Type myType in Types)
{
    if (myType.BaseType == null) continue;
    
    if (myType.BaseType == typeof(Form))
    {                    
        var emptyCtor = myType.GetConstructor(Type.EmptyTypes);
        if (emptyCtor != null)                    
        {
            var f = (Form)emptyCtor.Invoke(new object[] { });
            string FormText = f.Text;
            string FormName = f.Name;
            string btype = myType.BaseType.FullName;        

        }
    }
}

But each time when Form is accessed the Constructor is called and everything inside constructor is executed. How to avoid this?





Scala runtime reflections get all the members of a specific type even for inner classes

With scala 2.12.10

Suppose I want to implicitly convert at runtime a case class, in this case Special to a case class SpecialString. The implicit conversion is provided by a trait External. The name for SpecialString should be the declaration name of the class Special.

import scala.reflect.runtime.universe.{runtimeMirror, typeOf}
import scala.reflect.runtime.universe


case class Special(i: Int)
case class SpecialString(s: String)

trait External {
  val rm = runtimeMirror(getClass.getClassLoader)
  val im = rm.reflect(this)
  val members = im.symbol.typeSignature.members
  def specials: Iterable[universe.Symbol] = members.filter(_.typeSignature <:< typeOf[Special] )
  implicit def SpecialIntToString(s: Special): SpecialString = {
    val name = im.reflectField(specials.filter(x => im.reflectField(x.asTerm).get.asInstanceOf[Special] == s).head.asTerm).symbol.toString.replace("value ", "")
    SpecialString(s"name = $name")
  }
}

Currently I'm able to implicitly convert convert members declared inside a class extending the External trait.

class MyClass extends External {
  val firstSpecial = Special(1)
  val two = 2
  val specialS: SpecialString = firstSpecial
}

class MySecondClass extends MyClass {
  val specialS2: SpecialString = firstSpecial
}
val myClass = new MyClass
print(myClass.specialS) // SpecialString(name = firstSpecial)

But I'm not able to convert members that are declared in a super class

class MyClass {
  val firstSpecial = Special(1)
  val two = 2
  val specialS: SpecialString = firstSpecial
}

class MySecondClass extends MyClass with External {
  val specialS2: SpecialString = firstSpecial
}
val myClass = new MyClass
print(myClass.specialS)
val mySecondClass = new MySecondClass
print(mySecondClass.specialS2) // java.util.NoSuchElementException: next on empty iterator

Any help?





How can i check if a string property is nullable in c# 8 (with nullable enabled) [duplicate]

I want to check with Reflection if a property is nullable string. So my question is similar to this one (Correct way to check if a type is Nullable), except that for a string this does not work since it's not a valueType. Since c# 8 you can make a string property nullable, but i can't seem to distinguish it from a non-nullable property.

#nullable enable
public class User
{

    public string? Cid { get; private set; }
    public string Zid { get; private set; }
}

User user = new User();
System.Reflection.PropertyInfo property = user.GetType().GetProperty("Cid");
System.Reflection.PropertyInfo property2 = user.GetType().GetProperty("Zid");




lundi 14 décembre 2020

I have a setup where I want to have a method to handle different report templates (each template have less/more fields than the others) by passing in the report name and create the object at runtime. It shall then check if each field exists, and set the value if it does. The object will then be serialized to JSON for return.

I have a test setup as below. The problem is that I cannot get a list of fields of the created object. The object.getClass().getDeclaredFields() always give an empty array.

Would like to see if you can spot out any mistakes or if there is smarter way of doing this.

Main logic:

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

public class Test {

    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException,
            InvocationTargetException, NoSuchMethodException, SecurityException {
        Class<?> cls = Class.forName("CustomerReservationReportBasic");
        CustomerReservationReport customerReservationReport = (CustomerReservationReport) cls.getDeclaredConstructor()
                .newInstance();
        System.out.println(hasField(customerReservationReport, "name"));
    }

    public static boolean hasField(Object object, String fieldName) {
        return Arrays.stream(object.getClass().getDeclaredFields()).anyMatch(f -> f.getName().equals(fieldName));
    }
}

Model:

CustomerReservationReport

This is the parent class and all the fundamental report fields are here

import java.math.BigDecimal;

import lombok.Data;

@Data
public abstract class CustomerReservationReport implements Comparable<CustomerReservationReport> {

    private String name;
    private int num_of_visit;
    private BigDecimal total_spend;

    @Override
    public int compareTo(CustomerReservationReport customerReservationReport) {
        return this.getName().compareTo(customerReservationReport.getName());
    }
}

CustomerReservationReportBasic

This would be one of the various kinds of reports.

public class CustomerReservationReportBasic extends CustomerReservationReport {
    public CustomerReservationReportBasic() {
        super();
    }
}




In Go, is there anything like Java's Class.newInstance?

  1. I know there is no default constructor in Go.
  2. I want to new some "decoder" at runtime, according to received message's type.

So, what can I do? Use a map, key is the name of type, value is some wrapper function to init/new?





Get source code of a JavaScript class constructor

I need to create a method GetCode returning a string with the source code of a constructor function for any class. For instance,

let code = GetCode (class CX {
  constructor () {
    this.x = 1
    this.y = 1
    this.fx ()
    this.fy ()
  }
  fx () {}
  fy () {}
})

should return some similar than this in the code variable:

`
  this.x = 1
  this.y = 1
  this.fx ()
  this.fy ()
`

For regular methods such as fx or fy a simple .toString invocation is enough. But when that is done on the constructor function, the returned string is the whole text of the class and not the inner source code of the function. I have tried to parse the string returned by CX.toString () to fetch exactly the fragment of text I need using tools such as JSCodeShift but the fingerprint is too heavy (5Mb).

I wonder if would be possible to devise a hack to get the string with the source code I need.





How to pass vararg of different classes that inherit another class in Kotlin?

I'm trying to create a simple game in Kotlin. I have a BitmapContainer class which is inherited by another classes. Inheritors has init block and companion objects which contains list of bitmaps, so that they created once and used for all objets of the same type.

What I want is to create BitmapPreloader class, which has a vararg of BitmapContainer-derived classes and a callback. Preloader should create one instance of every class in vararg and invoke callback method.

The question is: how to pass classes that way? I just can't figure it out.

I don't know if it will be of help, but here's some of described code:

abstract class BitmapContainer(
val res: Resources,
val downScale: Float,
val onInitializationCompletedListener: (() -> Unit)? = null) {
protected fun createBitmap(
    @DrawableRes resId: Int,
    useFilter: Boolean = false
): Bitmap {
    BitmapFactory.decodeResource(res, resId).also {
        return Bitmap.createScaledBitmap(
            it,
            (it.width / downScale * Screen.ratioX).toInt(),
            (it.height / downScale * Screen.ratioY).toInt(),
            useFilter
        )
    }
}

protected fun createBitmapList(
    resIds: List<Int>,
    useFilter: Boolean = false
): List<Bitmap> = ArrayList<Bitmap>().apply {
    resIds.forEach {
        this.add(createBitmap(it, useFilter))
    }
}

BitmapContainer example:

class GroundTileBitmapContainer(
res: Resources,
downScale: Float,
listener: (() -> Unit)? = null) : BitmapContainer(res, downScale, listener) {

init {
    if (bitmap == null) {
        bitmap = createBitmap(R.drawable.ground_02)
    }
}

companion object {
    var bitmap: Bitmap? = null
}

}

What I want to do in Preloader:

lass BitmapPreloader(
vararg classList: Any?, //That is the line I have no idea how to do
callback: () -> Unit) {

init {
    classList.forEach { it::class.createInstance() }
    callback.invoke()
}




dimanche 13 décembre 2020

NoSuchMethodException not caught

I am trying to catch the NoSuchMethodException in the following code:

try {
    method = currentClass.getMethod(arg1,arg2);
    break;
} 
catch (NoSuchMethodException e) {
    System.out.println("hi");
}

It's not getting caught. I've tried catch (Throwable e) and catch (Exception e) and catch (NoSuchMethodError e) but none of them worked.

Even though When I run the code the console shows a NoSuchMethodException, but it's not getting caught.





How do I reflect nullability of a type's property in C# 9 when Nullable Reference types are enabled? [duplicate]

I am iterating the reflected properties of a type. I want to know which have been defined as nullable, and which are not. I believe the usual approach is:

 Nullable.GetUnderlyingType(property.PropertyType) != null

I am using .NET 5.0 and opted into Nullable reference types. Unfortunately this always returns False for both string and string?, whereas I expected the latter to be 'True'.

Project File

<TargetFramework>net5.0</TargetFramework>
<Nullable>enable</Nullable>

Type

public record MyRecord
(
    string ANonNullableProperty,
    string? ANullableProperty
);

Nullable Test

foreach (var property in typeof(MyRecord).GetProperties())
{
    bool isNullable = Nullable.GetUnderlyingType(property.PropertyType) != null;
    Console.WriteLine($"Property {property.Name} null: {isNullable}");
}

Expected Output

Property ANonNullableProperty null: False
Property ANullableProperty null: True

Actual Output

Property ANonNullableProperty null: False
Property ANullableProperty null: False

Is this a subtle defect, or have I misunderstood something? Is there a workaround or another way?





samedi 12 décembre 2020

Python reflection: How to get the id of a specific instance of a method from inside itself?

I can't just use something straightforward like id(self.methodname) because the scenario is a little more complicated than that since I'm doing funky dynamic stuff. I'll try to explain the whole situation clearly.

class A:
     def __init__(self):
         self.ax = 10
     def amethod(self, other):
         print(self.ax)
         print(other.bx)

class B:
     def __init__(self):
         self.fun_dict = {}
         self.bx = 20
     def run_in_dict(self):
         for fn in self.fun_dict.values():
             fn()

First we have two classes. One of them has a dictionary that will contain functions as values and those function's ids as keys. In the actual program this is for storing callback functions, and fun_dict is instead named something like on_receiving.

a = A()
b = B()
import types
bound_to_b = types.MethodType(a.amethod, b)
print(bound_to_b)  # <bound method A.amethod of <__main__.B object at 0x7fdcdacf1850>>
print(bound_to_b())  # prints 10 and 20
b.fun_dict[id(bound_to_b)] = bound_to_b
b.run_in_dict() # also prints 10 and 20
a.ax = 2
b.run_in_dict() # prints 2 and 20, as expected

So far so good. All of this is working as intended: we now have a method bound_to_b that's bound to two objects simultaneously, and it's been stored in b's fun_dict. Yes, I know this is kind of horrible code but it's a learning project so don't worry, nobody will be exposed to it.

But now let's say I later want to remove the bound method from b. That is, remove its reference from b.fun_dict. This is easy enough if I'm doing it from outside and have the id saved somewhere else, but my question is: Is there a way to do it from inside amethod without storing the id? Or if it's not possible, is there something other than the id that can be used as a dict key that would make it possible?

print(id(self.amethod)) in fact prints a different memory position every time, so it doesn't help. Nothing else inside dir(bound_to_b) jumps out at me either.





Dora Spring implement it's own packages scan

Does Spring implements it's own way to scan the class in packages or does it use a external library like 'reflection':

https://github.com/ronmamo/reflections





How to write analyzes to analysis of multilevel inheritance in c#

I'm using Roslyn I'm trying to do something like below

I have a file to analysis

Class1.cs
Using.... 
Using.... 
Namespace {
Class1:class2

}


Class2.cs
Class2:class3
{   

}

I need to know what is the namespace/dll of class3 using c#roslyn analyzer Recurrsivly

NOTE- I'm analyzing class1.cs and want to know class1 inherited which class (ie class2) and if class2 is inherited any class need to know that's inherited class dll name (class3's dll/assembly name)