samedi 31 août 2019

Using reflection to iterate a class with nested classes

I found this answer here at SO, Get nested property values through reflection C#, though it also tries to dump e.g. a string's properties, which then throws an exception.

My classes look like this

public class MyModels
{
    public int Id { get; set; }
    public DateTime EditDate { get; set; }
    public string EditBy { get; set; }
}

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

public class Organization
{
    public Person Person { get; set; }
    public Organization()
    {
        Person = new Person();
    }

    public string Name { get; set; }
}

public class Company : MyModels
{
    public Organization Organization { get; set; }
    public Company()
    {
        Organization = new Organization();
    }

    public string Description { get; set; }
}

And here's the code from the linked answer

var objtree = "";
void DumpObjectTree(object propValue, int level = 0)
{
    if (propValue == null)
        return;

    var childProps = propValue.GetType().GetProperties();
    foreach (var prop in childProps)
    {
        var name = prop.Name;
        var value = prop.GetValue(propValue, null);

        // add some left padding to make it look like a tree
        objtree += ("".PadLeft(level * 4, ' ') + $"{name} = {value}") + Environment.NewLine;

        // call again for the child property
        DumpObjectTree(value, level + 1);
    }
}
DumpObjectTree(itemData);


How do I make it to not try to dump properties on string, datetime, etc.?





vendredi 30 août 2019

How i can change method annotations value in RunTime?

I have controller like

@MessageMapping("/room.register")
@SendTo("#{sendTo}")
public Message addUser(@Payload Message message,
                       SimpMessageHeaderAccessor headerAccessor) {
    headerAccessor.getSessionAttributes().put("username", 
    message.getSender());
    return message;

}

And i want to change value of SendTo annotation in runtime.

I tried to do it as follows:

@Aspect
public class SendToAspect {
@Autowired
private WebSocketConfigurationProperties webSocketConfigurationProperties;


@Around("execution (public * *(..)) && @annotation(ann)")
public Object execute(final ProceedingJoinPoint point, final SendTo ann) 
throws Throwable {

    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    method.setAccessible(true);

    Annotation[] annotations = method.getDeclaredAnnotations();
    for (int i = 0; i < annotations.length; i++) {
        if (annotations[i].annotationType().equals(SendTo.class)) {
            annotations[i] = new SendTo() {

                @Override
                public Class<? extends Annotation> annotationType() {
                    return SendTo.class;
                }

                @Override
                public String[] value() {
                    return new String[] 
                            {webSocketConfigurationProperties.getTopic()};
                }
            };
        }
    }
    return point.proceed();
}

}

but this only changes in the annotation array (Annotation[] annotations) and in the method annotations (method.getDeclaredAnnotations()) does not change.

Please tell me how to do this and is it possible at all?





how do i get a class name variable

Im trying to get the class variable name

static void Main()
{
    TaskAction m_first = new TaskAction();
    m_first.Increment();
    m_first.Increment();

    TaskAction m_Second = new TaskAction();
    m_Second.Increment();

}

public class TaskAction
{
    private int m_Current;

    public TaskAction()
    {
        m_Current = 0;

    }

    public void Increment()
    {
        m_Current++;
        write(" TaskAction " + vairableName + " "  + m_Current);       
    }
}

i want to it to write out:

TaskAction m_first 1

TaskAction m_first 2

TaskAction m_second 1





Using dll that references assemblies already in project

So I have a project in Unity that is supposed to be able to load and instantiate classes from an assembly exported from another program. It goes like this:

  1. Necessary files are exported as DLL from Unity project
  2. Other program loads this DLL and uses it to make a new class (i.e. calling methods in the original Unity app), which it then compiles to another DLL
  3. Original Unity app loads this DLL and runs the newly created class

However, when I get to step 3, its like functions in the original Unity project are duplicated and I get conflicts. I guess this makes sense because when you compile the DLL it has to resolve all references.

I then tried doing it so the original Unity project would take the code generated by the other program (text, as opposed to the dll) and compile it at runtime. This worked on Windows, but the problem is that this is an Android app and when I build to the phone, I get the following exception using CSharpCodeProvider to compile:

2019/08/29 14:40:45.424 20040 20069 Error Unity DirectoryNotFoundException: Could not find a part of the path "/tmp/a6icqx2c.tmp".
2019/08/29 14:40:45.424 20040 20069 Error Unity at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) [0x00164] in <7d97106330684add86d080ecf65bfe69>:0 
2019/08/29 14:40:45.424 20040 20069 Error Unity at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean isAsync, System.Boolean anonymous) [0x00000] in <7d97106330684add86d080ecf65bfe69>:0 
2019/08/29 14:40:45.424 20040 20069 Error Unity at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access) [0x00000] in <7d97106330684add86d080ecf65bfe69>:0 
2019/08/29 14:40:45.424 20040 20069 Error Unity at (wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess)
2019/08/29 14:40:45.424 20040 20069 Error Unity at System.CodeDom.Compiler.TempFileCollection.EnsureTempNameCreated () [0x00076] in <0079a30f96a047348857e1cecc6c638a>:0 
2019/08/29 14:40:45.424 20040 20069 Error Unity at System.Co

Unfortunately, the rest is cut off. I tried using Roslyn and got a DirectoryNotFoundException as well. Does anyone know either how I can fix this exception, or make the DLL file in the other app so that it will call the methods correctly in the original app?





jeudi 29 août 2019

How to copy a non-pointer value to a pointer indirected value via reflection

I want the Set method below to set the APtr field of a passed in B struct to a value that gets passed in by value, i.e. without a pointer indirection.

For that to work via go reflection, I will probably have to copy that value to a new location that I have the address of? Either way, how can I get this to work? What I have is a working version for non-pointers values.

type A struct {
    AnInt int
}

type B struct {
    AnA   A
    APtr *A
}

func Set(strukt interface{}, fieldName string, newFieldValue interface{}) {
    struktValueElem := reflect.ValueOf(strukt).Elem()
    field := struktValueElem.FieldByName(fieldName)
    newFieldValueValue := reflect.ValueOf(newFieldValue)
    if field.Kind() == reflect.Ptr {
        // ?? implement me
    } else { // not a pointer? more straightforward:
        field.Set(newFieldValueValue)
    }
}

func main() {
    aB := B{}
    anA := A{4}
    Set(&aB, "AnA", anA) // works
    Set(&aB, "APtr", anA) // implement me
}

Playground: https://play.golang.org/p/6tcmbXxBcIm





Iterate through value of an object

I have and object say Object abc = new List<myclass>();

currently abc is of Type Object and pocess 1000 records say. What my need is to iterate through these values.

Is there a way to do this?





Get all only types used in the project from all included assemblies

How does it possible to have all used types of an assemblies used in the project? Let's have a project which uses some other assemblies (uses some types from them). I want iterate all only types (by reflection) which are used in the main project and nothing more. Is it really possible?

Thank you.





Getting methods from reflection and assigning them to delegate

I want to get all methods from class through reflection and assign them to created delegate or instantiate new delegete with them.

I am trying to learn reflection and delegates and I want to use reflection here because I don't like the way it look like with +=

I tried to assign with Delegate.CreateDelegate method but there isn't any overloads that get array of MethodInfo which I get from reflection.

    public delegate void GetIntegersPower(int x);
class Program
{

    static void Main(string[] args)
    {
        GetIntegersPower iP = Power.Square;
        iP += Power.Cubed;
        iP += Power.xToThePowerOfFour;
        iP += Power.xToThePowerOfFive;
        iP += Power.xToThePowerOfSix;
        var powerMembers = typeof(Power).GetMethods();
        var del=(Action<int>)Delegate.CreateDelegate(typeof(Action<int>), powerMembers[0]); //error
        del(3);
        Console.ReadKey();
    }
}
class Power
{
    public static void Square(int x) => Console.WriteLine($"The number of {x} to the power of two equals {x * x}" + Environment.NewLine);
    public static void Cubed(int x) => Console.WriteLine($"The number of {x} to the power of three equals {x * x * x}" + Environment.NewLine);
    public static void xToThePowerOfFour(int x) => Console.WriteLine($"The number of {x} to the power of four equals {x * x * x * x}" + Environment.NewLine);
    public static void xToThePowerOfFive(int x) => Console.WriteLine($"The number of {x} to the power of five equals {x * x * x * x * x}" + Environment.NewLine);
    public static void xToThePowerOfSix(int x) => Console.WriteLine($"The number of {x} to the power of six equals {x * x * x * x * x * x}" + Environment.NewLine);
}

Now I am able only to execute one method when I supply to MethodInfo index but I want to create multicast delegate





mercredi 28 août 2019

How to use default property file to set fields in a test object instead of using ReflectionTestUtils

I am writing a test for a service in springboot and used @InjectMocks for creating the test object. In the test object, there are a lot of fields which are being set from properties file using @Value. I want to set these fields on the test object directly from the properties file instead of ReflectionTestUtils as there are many fields.

Inside Service Class :

@Value("#{${field1}}")
private Integer field1;

@Value("#{${field2}}")
private Double field2;

Inside test class

    @RunWith(SpringRunner.class)
    @ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
    @TestPropertySource(properties = {
            "feild1=100",
            "feild2=1.9"
    })
    public class ServiceTest{

    @InjectMocks
    Service serviceObj;

    @Before
    public void setup(){
        ReflectionTestUtils.setField(serviceObj , "field1" , 100);
        ReflectionTestUtils.setField(serviceObj , "field2" , 1.9);
    }

I want to set all the fields directly from properties file in the unit test as spring is doing in the main app.





Java - Relocate references at runtime

So first off I know that you can relocate all references your compiled jar with various shadow plugins on different build systems. I know how that works and am already using it. However I ran into a problem where I can't do that at compile time.

I'll simplify my situation so it's easier to understand (but I'll explaining the full picture at the bottom, in case you are curious).
I'm writing a plugin for two different (but similar) systems (one jar forall). Those platforms are in charge of starting the underlying software and loading/starting all plugins (so I don't have control over the application).
Platform A offers me a library (let's call it com.example.lib). And so does platform B. But it decided to relocate it to org.b.shadow.com.example.lib.
Now in the core code (the code used on both platforms) of my plugin I use the library. Now while I can detect on which platform I am on, I currently do not know how I can rewrite all references in my code to the library at runtime so it works on platform B.

From what I've found it seems like I need to use a custom ClassLoader to achieve that. The issue here being that I don't know I could make the runtime use my custom ClassLoader. Or where to start really.
One important thing is that those relocations may only affect references in classes from my packages (me.brainstone.project for example).
Another dependency I use (and have shaded in) uses ASM and ASM Commons, so if it is possible doing it with those, that would be amazing!

So in summary. I would like to optionally relocate references (to other classes) in only my classes at runtime.


Now here is a a bit more detailed explanation of my setup.
Fist I'd like to preface that I am aware that I can just create two different jars for the different platforms. And I am already doing that. But since surprisingly many people can't seem to figure that out and I'm getting tired of explaining it over and over again (those are the people that wouldn't read docs to save their lives) I'd like to just offer a single jar for both, even if it means I need to spend a significant time on getting it to work (I much prefer this over constantly explaining it).
Now my actual setup looks like this: On platform A the library is provided but on platform B it isn't. I know that other plugins often use the library by shading it in (many not relocating causing all kinds of issues). So to prevent any conflicts I download the library, relocate the classes inside that jar with jar-relocator and then inject it into the classpath using reflections. Downside in this case I currently cannot use the library if it's relocated. That's why I'd like to change the references in my code at runtime. And it also explains why I don't want to change the references of other classes, because I don't want to accidentally break those other plugins. I also think that if I can somehow use my own ClassLoader that I don't need to inject jars into the main ClassLoader because then I can just tell that ClassLoader to use the additional jars without having to resort to reflections.
But as I said, from what I understand the problem is the same as in the simplified version.





How to change By class at runtime to generate dynamically changing xpath?

In my current framework locators of By class are being changed dynamically say for suppose ok and cancel have same xpath expression except the text Ok and one has text cancel in it then it uses a method called

findElement(driver,generateDynamicPageElements(By b,String s));

where b definition is

By b = By.xpath("//button[text()='{param1}']");

And

s="OK";

Then at runtime it changes the functionality and turns into findElement(driver,By.xpath("//button[text()='OK']")); finds button with text OK how can I achieve it? Since the functionality of generateDynamicPageElement is hidden so I needed to ask this question.





mardi 27 août 2019

Reflectively set field of struct that was passed in as interface{}

The following works fine:

type MyStruct struct {
    MyField int32
}

func SetReflectConcrete(obj *MyStruct, fieldName string, newValue interface{}) {
    objElem := reflect.ValueOf(obj).Elem()
    field := objElem.FieldByName(fieldName)
    field.Set(reflect.ValueOf(newValue))
}

func main() {
    myStruct := MyStruct{123}
    SetReflectConcrete(myStruct, "MyField", int32{1234})
}

How can I make a variant of the SetReflect function that works on any struct? All my attempts so far have failed. The signature would be something like this:

func SetReflectInterface(obj interface{}, fieldName string, newValue interface{})

And is this even possible, when calling it like

SetReflectInterface(myStruct, "MyField", int32{1234})

or would it have to be called like

SetReflectInterface(&myStruct, "MyField", int32{1234})

(After all, interface{} has a pointer to the struct.)





In Spring AOP, what is the difference between joinPoint.proceed and method.invoke?

I don't know the difference between the two methods, because they all work very well.

The reason I tried to use method.invoke is that I want to call other methods instead in the aspect.

@Component
public class DefaultApiInvokeFacadeImpl implement ApiInvokeFacade {
    @Override
    public ResponseDTO request(RequestDTO request,Class bodyClazz) {
        return request(request,bodyClazz,null);
    }
    @Override
    public ResponseDTO request(RequestDTO request,Class bodyClazz,InvokeContext invokeContext) {
        // .... some codes
        return response;
    }
}

@Component
@Aspect
public class HttpInvokeAspect {

    @Pointcut("execution(" +
            "public io.github.lvyahui.http.api.model.ResponseDTO io.github.lvyahui.http.api.facade.impl.DefaultApiInvokeFacadeImpl" +
            ".request(..)" +
            ")")
    public void httpApi() {
    }

    @Around("httpApi()")
    public Object arroud(ProceedingJoinPoint joinPoint) throws Throwable {
        Object [] args = Arrays.copyOf(joinPoint.getArgs(),3);
        Method method = joinPoint.getSignature().getDeclaringType().getDeclaredMethod("request", RequestDTO.class,
                    Class.class, InvokeContext.class)
        // A
        /// Object ret = joinPoint.proceed(args);
        // B
        Object ret = method.invoke(joinPoint.getTarget(),args);
        return ret;
    }
}





Return properties of a class who's getters use custom Get method

I have a TransactionData2ClassAction subclass which looks something like this:

  public class TransactionData2ClassAction : Entity
  {
    public int       TransactionId        => Get<int>();
    public int       FundId               => Get<int>();
    public string    PortfolioCode        => Get<string>();
    public string    SecuritySymbol       => Get<string>();
    public string    SecurityTypeCode     => Get<string>();
    public DateTime  TradeDate            => Get<DateTime>();
    public DateTime? SettleDate           => Get<DateTime?>();
    public decimal   Quantity             => Get<decimal>();
    public decimal   Amount               => Get<decimal>();
    public decimal   SecFee               => Get<decimal>();
    public string    BrokerCode           => Get<string>();
    public short     TaxLotNumber         => Get<short>();
    public string    TransactionCode      => Get<string>();
    public decimal   CommissionAmount     => Get<decimal>();

    public int TestProperty { get; }
  }

The Entity base class looks something like this:

public class Entity : INotifyPropertyChanged, IDataErrorInfo
  {
    protected T Get<T>([CallerMemberName] string aColumnName = null, DataRowVersion? aDataRowVersion = null)
    {
      // Details.
    }

    protected string Get(CompressionEncryptionOptions aOption, [CallerMemberName] string aColumnName = null)
    {        
      // Details.
    }        
  }

My questions is how do I return properties who's getters use either of the Entity base class Get methods?

For example, the result would return all properties except TestProperty.

I have this so far:

public static PropertyInfo[] GetTransactionData2FieldsFromEntityUsingProperties(Type aEntityType)
{
  if (!aEntityType.IsSubclassOf(typeof(Entity)))
    throw new InvalidOperationException("Wrong type.");

  return aEntityType.GetProperties().Where(aProperty => aProperty.CanRead && aProperty.GetAccessors().Any(aMethodInfo => aMethodInfo.IsAssembly || aMethodInfo.IsPublic)).ToArray();
}





IsAssignableFrom does not work when versions do not match

I have interface A defined in A.dll version 3.0 I have B.dll which references A.dll 3.0 and implements interface A in class B.

I now have the same A.dll, identical in every way except it is version 3.1.

I try to load B.dll referencing version 3.0 of A.dll. But 3.1 is loaded in memory.

 var assembly = Assembly.LoadFile(dllPath);
        var types = assembly
            .GetTypes();
        var extensionClass = types
            .First(x => typeof(T).IsAssignableFrom(x) && x.IsClass);
        _logger.Debug.Log($"Creating instance for {dllPath} of type {extensionClass.FullName}");
        var instance = (T)Activator.CreateInstance(extensionClass);
        return instance;

But that does not work.

I get sequence contains no matching elements.

I cannot use an App.config to do an assembly redirect as the code loading B.dll is running inside a host process out of my control.

What can I do aside from keeping A.dll at the same version forever?





Dynamic grouping by specific attributes with sorting

My problem is solved by the below answer except sorting on grouped attributes.

Dynamic grouping by specific attributes with Collection.stream

How can i retrieve list from values set in sorted order based on the attributes in ascending or descending order. One group attribute can be ascending while other can be descending.





How to search for method usage on a .java file?

My application searches for some methods via reflection. Then, I need to search for the usage of those methods on some .java files. Right now I am able to match the method name, and number of arguments, but not the type of the argument.

For example: .get("testObject") gets matched by the method signature .get(java.lang.String) , which is correct, and the method .get(java.lang.Boolean), because of the same method name ("get") and number of arguments (1 argument).

How can I manage to also check for the type? Is there any efficient way, or literature, on finding method usage inside text (or .java) files? I could not find much.

Any help is appreciated.





Java reflection getDeclaredMethod throws NoSuchMethodException

I have a private method getListSonarMetricsFromRegistry declared in the Class SonarRestApiServiceImpl that I want to call, with Java reflection, but I get the exception:

java.lang.NoSuchMethodException: com.cma.kpibatch.rest.impl.SonarRestApiServiceImpl.getListSonarMetricsFromRegistry(java.util.HashMap)
at java.lang.Class.getDeclaredMethod(Class.java:2130)
at com.cma.kpibatch.service.rest.SonarRestApiServiceImplTest.testGetListSonarMetricsFromRegistry(SonarRestApiServiceImplTest.java:81)


I tried to use Java reflection, like below :

    @Test
    public void initTest() throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Map<Long, KpiMetric> tmp = new HashMap<>();
        Method method = sonarRestApi.getClass().getDeclaredMethod("getListSonarMetricsFromRegistry", tmp.getClass());
        method.setAccessible(true);
        List<String> list = (List<String>) method.invoke(sonarRestApi, registry.getKpiMetricMap());
    }


Here is the getListSonarMetricsFromRegistry method declaration:

//This method works correctly, it returns a List of String without error
private List<String> getListSonarMetricsFromRegistry(Map<Long, KpiMetric> map) {
    return //something
}

The similar questions provided by Stackoverflow did help, but I still have the same Exception.





c# Reflection compare propery values

I am trying to build the most budget of ORMs.

I have 2 objects, one "item" and one "original", when creating item, i simply save a COPY of it, in a variable called original. The copy is created via an extension i stole from this post https://stackoverflow.com/a/11308879/10647851

So i want to build my update query, very simple i thought.

foreach (PropertyInfo prop in properties) {
   var one = prop.GetValue(original, null);
   var typeOne = one.GetType();
   var two = prop.GetValue(item, null);
   var typeTwo = two.GetType();

   if(one != two) { ... }
}

However, one is unequal to two in several cases where you would not expect it.

The ID (type in the model = int?) 2703 is unequal to 2703. I stepped through the code and the type is Int32. Booleans are problems too. Strings work. DateTime?'s work.





How to "invoke" PropertyInfo of type Action<,> in runtime

I have a generic class and a property of type Action<,>. I am wondering if there is a way to actually invoke this delegate using reflection in runtime, not just set value to this class property (via PropertyInfo.SetValue).

I tried a lot of things, like using expressions, dummy casting, read forums, but none of the solutions worked for me.

Workaround: What I could think of is creating a dummy method which internally calls the delegate, and with reflection is fairly easy to invoke this method.

public class Student
{
    public string Name { get; set; }
}

public class ConfigData<T> 
    where T: class
{
    public Action<T, object> ValueInjector { get; set; }

    public void SetValue(T entity, object valueToSet)
    {
        this.ValueInjector(entity, valueToSet);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var configObj = new ConfigData<Student>()
        {
            ValueInjector = (x, y) =>
            {
                // Some custom logic here
                x.Name = y.ToString();
            }
        };

        // Parameters
        Student student = new Student();
        object valueToSet = "Test";

        Type configType = configObj.GetType();
        PropertyInfo propertyInfo = configType.GetProperty("ValueInjector");

        // Invoke the property info somehow with the parameters ?

        // Workarround - invoke a dummy method instead
        MethodInfo methodInfo = configType.GetMethod("SetValue");
        methodInfo.Invoke(configObj, new object[] { student, valueToSet });

        Console.WriteLine(student.Name);
    }
}

I want to be able to invoke the propertyInfo variable and pass to it the two parameters I already have (student, valueToSet), since I know that it represent a delegate which can be run.





lundi 26 août 2019

Using reflection to reduce enum boilerplate?

Recently, I found this handy little snippet of code to get the string representation of an enum, even when associated values are present:

enum XXX {
    case a
    case b
    case c(Int)

    private var typeStr: String {
        guard let label = Mirror(reflecting: self).children.first?.label else { 
            return .init(describing: self) 
        }
        return label
    }
}

This is pretty clever. Could reflection also be used to reduce boilerplate like this init function?

init?(rawValue: String?)
{
    guard let val = rawValue?.lowercased() else {
        return nil
    }
    switch val {
        case "a", "1a": self = .a
        case "b", "1b": self = .b
        case "c", "1c": self = .c(1)
        default: return nil
    }
}





Expression Tree of a Generic Action

I need to build an expression tree out of Action (if I may formulate it this way) but the problem is that the type T is determined at runtime via reflection.

I need to pass this expression as an argument to a generic method that gets called using the MethodInfo.Invoke API. The type argument for this method and the lambda mentioned above should match.

Is this achievable? Or maybe there are some better / easier ways of doing this?





Verify that a method of a regular (non-mock) object was called via reflection

I have code that looks like this:

abstract class Parent {
   public void dispatch(...) { ... }
}

The job of the dispatch method is to determine which method of the subclass should be called based on the value of the parameters, and then call it; this is done via runtime annotation analysis. So, if I have a subclass that looks like this:

class Child extends Parent {
    @CallThisMethodIfA
    public Thing aMethod(...) { ... }

    @CallThisMethodIfB
    public Thing bMethod(...) { ... }
}

then calling child.dispatch(A) should invoke aMethod (where child is an instance of Child). Of course, I'm simplifying as much as possible here - these aren't the actual annotations and args that I have.

My question is how to test this behavior. I tried something like:

Child child = new Child(...);
child.dispatch(A);
verify(child, times(1)).aMethod(...)

which gave me a NotAMockException because, of course, child is not a mock but a real object. I'm not 100% certain on how spying works, but I also tried instantiating Child using @Spy, and while that didn't throw an exception it also didn't register a call to aMethod because, I'm guessing, spying doesn't actually imitate the internal behavior of the class. How would I go about doing this? I guess I could manually initialize Child and make aMethod return a very specific instance of Thing that I can then check, but that doesn't feel clean to me (what if some other method just so happens to return an equal instance?)





Diff two classes structure

My task

Force two classes to have the same (or similar) structure

Description

I have an entity and DTO. How do I force that if someone adds / removes / changes a field in entity, a test will fail, so DTO structure matches the entity structure.

Using so called diff tool

Let's imagine a diff tool which has input parameters - two objects and output parameter - Map, where Diff is a structure oldValue, newValue. This tool returns difference between input arguments.

public Map<String, Diff> diff(final Object first, final Object second) {
    // This is implemented.
    return innerDiff(first, second, otherParameters); // 
}

public class Diff {
    private String oldValue;
    private String newValue;
    // getters, setters, constructor.
}

// To achieve this, we used Guava Plain map. It works well!

How do I achieve the same for classes. I want to diff two classes and have their fields as difference.

public Map<String, FieldDiff> diff(Class<?> type1, Class<?> type2) {
    // How?
} 

One idea is to use reflection and iterate though all fields of the class.





cast reflected result from object to list

how can i cast reflected result from object to list???

                Type tSource = item.SourceType;     //enum
                Type tDest = item.DestinationType;  //enum

                MethodInfo method = typeof(EnumConverters).GetMethod("GetEnumValues");
                MethodInfo methodGenericSource = method.MakeGenericMethod(tSource);
                object enumsSource = methodGenericSource.Invoke(null, null);
                //i need to convert enumsSource to List<tDest> (where tDest is enum)

                List<tDest> list = ???

exist some reflection function like "getResultGeneric" or "getResultOfType" ?!!?!?





automapper map with reflection

i'm trying to make an automapper helper function that checks conversion of enums (where i've custom business logic in mappers)
mapper is an instance, non static.

            var cfgExp = new MapperConfigurationExpression();
            cfgExp.AddProfile<ProfileXXX>()
            MapperConfiguration mapConfig = new MapperConfiguration(cfgExp);
            IMapper mapper = new Mapper(mapConfig);
            mapper.ConfigurationProvider.AssertConfigurationIsValid();
            mapper.AssertEnumConversion(cfgExp);

public static void AssertEnumConversion(this IMapper @thisMapper, MapperConfigurationExpression cfgExp) { try { if (@thisMapper == null) throw new ArgumentNullException(nameof(@thisMapper));

            List<TypePair> enumMapping = cfgExp
              .Profiles
              .SelectMany(x => x.TypeMapConfigs)
              .Where(x => x.Types.SourceType.IsEnum)
              .Select(x => x.Types)
              .ToList();


            MethodInfo methodMap = @thisMapper
                .GetType()
                .GetMethods()
                .Where(x => x.Name == "Map" && x.IsGenericMethod)
                .ToList()[0];//here i've seen 6 mappers  take first //TDestination Map<TDestination>(object source)

            foreach (var item in enumMapping)
            {
                Type tSource = item.SourceType;
                Type tDest = item.DestinationType;

                //here i've an helper to take a ienumerable<Enum>
                MethodInfo method = typeof(EnumConverters).GetMethod("GetEnumValues");
                MethodInfo methodGenericSource = method.MakeGenericMethod(tSource);
                object enumsSource = methodGenericSource.Invoke(null, null);

                IEnumerable<int> enumIenumInt = enumsSource as IEnumerable<int>;
                if (enumIenumInt == null)
                    throw new ApplicationException($"enumIenumInt==null ({tSource.FullName} to {tDest.FullName})");

                Array enumArray = Array.CreateInstance(tDest, enumIenumInt.Count());
                foreach (var e in enumArray)
                {
                    MethodInfo methodMapGeneric = methodMap.MakeGenericMethod(tDest);
                    methodMapGeneric.Invoke(@thisMapper, new object[1] { e });//here i've exeption
                }
            }
        }
        catch (Exception e)
        {
            throw;
        }

but i receive exception like mapper is not initialized... where i'm wrong!?!?





dimanche 25 août 2019

Is there a way to declare method that takes any lambda as parameter?

I'm trying to write a method in C# that will accept lambda of any type, but I can't figure out how to do it.

I'm developing a class that will process text commands. I want to implement it in such a way that arguments will be automatically determined from lambda expression that handles particular command.

Here is an example of what API I would like to get:

commandProcessor.AddCommand("setpos", (int x, int y)=>{
    //do stuff
});
commandProcessor.AddCommand("changename",(string newName)=>{
    //do completely different stuff
});

And my command processor will look like this:

Dictionary<string, MagicType> mCommands;

public void AddCommand(string commandName, MagicType commandHandler){
    mCommands[commandName] = commandHandler;
}

Is there a MagicType that I can use or maybe I should use a completely different approach?





samedi 24 août 2019

Using a class name string as a generic type parameter

I have an Unpack() function that takes a generic parameter T where T is a class i.e.

var test = Unpack<ExampleClass>();

The above example works fine, but I am in a situation where I need to do the same as above, but I only know the class/generic parameter name in a string. In other words, how can I do the same thing as above with:

string className = "ExampleClass";

instead of the class ExampleClass?





Getting a reference to all objects of a type in class in C#

Say I have a class with reference variables to some objects of type Foo. Say I now want to get a list of all of these variables dynamically, meaning if I add a new one that one will also be in the list.

I have tried using reflection, but I am not very experienced with it, so I think that is the right way but I'm not completely sure.

public class Foo() {
    public void Setup() {
        // Runs some code
    }
}

public class MyClass() {
    public Foo a;
    public Foo b;
    public Foo c;
    public Foo d;
    public Foo e;

    // Current constructor, does what I want but in a non-elegant way
    MyClass() {

        Foo[] foos= new Foo[] {
            a,
            b,
            c,
            d,
            e
        };
        foreach(Foo foo in foos) {
            foo.Setup();
        }
    }

    // The constructor I want, with GetAllMembersOfType<T>() dynamically
    // returning new objects as I add them to the class later
    MyClass() {

        Foo[] foos = GetAllMembersOfType<Foo>();
        foreach(Foo foo in foos) {
            foo.Setup();
        }
    }
}

How could I create a method like GetAllMembersOfType<T>()? Or at least a way to call Setup() on all member variables of type Foo?





vendredi 23 août 2019

Dynamically choose class from string

I'm trying to be able to get an instance of a class based on a passed string ClassName without a bunch of IFs.

Class - ICLass

Public Function DoSomething()
End Function

Class - Class1

Implements IClass
Public Function iclass_dosomething()
    Debug.Print "Done from class1"
End Function

Class - Class2

Implements IClass
Public Function iclass_dosomething()
    Debug.Print "Done from class2"
End Function

Module1 - test module

Sub GetInstanceOf(ByVal s As String, ByRef Result As Object)
    Dim vbComp As Object
    Dim CodeString As String
    Set vbComp = ThisWorkbook.VBProject.VBComponents.Add(1)
    CodeString = "Sub foo(ByRef Result as Object)" & vbCrLf & _
            "Set Result = New " & s & vbCrLf & _
        "End Sub"
    vbComp.CodeModule.AddFromString CodeString

    Application.Run vbComp.Name & ".foo", Result
    ThisWorkbook.VBProject.VBComponents.Remove vbComp
End Sub

Sub Testing()
    Dim ClassName As String
    ClassName = "Class2"
    'ClassName = "Class1"
    Dim c As IClass
    Set c = New Class1
    GetInstanceOf ClassName, c
    c.DoSomething
End Sub

I'm getting

Done from class1

I'm expecting

Done from class2





Fetch Pagefactory WebElement name using reflection

src/test/resources/com/simulator/files/NewDownList.txt I am using selenium pagefactory, and have introduced an annotation @Name(Description = "Username"), which I use for all WebElements. I need to find the value for Description in my custom methods later on, for reporting, like:

public static void click(WebElement element) throws Throwable {
        try {
            element.click();
        } catch(ElementNotInteractableException E1) {
            throw new UnableToInteractWithElementException("Unable To Interact With " + WebElement Descriptionn);
        }
    }

My @Name annotation interface and pagefactory look like this:

Name Interface

@Target({ElementType.FIELD, ElementType.TYPE,ElementType.CONSTRUCTOR})
public @interface Name {    
    String Description() default "";
}

@Name(Description = "Username")
@FindBy(id="txtLoginID")
public WebElement username;

The problem I face while using reflections is the need to define classname of pagefactory , and also provide fieldname as string "username" , to retrieve the annotation value.

I wish to be able to retrieve the annotation value by only providing my WebElement and no other object to my click(WebElement element) method.





Set struct field which is a pointer using reflection

My question is like this one but with a slight difference that my value is an interface{}.

Let assume we have a struct like this:

type User struct {
    ID         int
    Email      string
    ResourceID *int
}

and a function that sets values of input struct.

func setFieldValue(s interface{}, fieldName string, value interface{}) {
    v := reflect.ValueOf(s).Elem()
    fieldVal := v.FieldByName(fieldName)

    if fieldVal.Kind() == reflect.Ptr {
        // Here is the problem
        fieldVal.Set(reflect.ValueOf(&value))
    } else {
        fieldVal.Set(reflect.ValueOf(value))
    }
}

It is obvious that if I run the code I get the following error:

panic: reflect.Set: value of type *interface {} is not assignable to type *int

What should I do to fix this?





Get Type from System.RuntimeType

How can I get the type (picture below) Application.Model.Person instead of System.RuntimeType for this case?

enter image description here Thank you.





jeudi 22 août 2019

How to get real list of object properties and its values

I have className in string variable and its Id:

string className = "Solution.TestClass"
long id = 1;

I'm using nHibernate to get entity from DB by its type and ID and its works but the returned object is has object type.

Type t = Type.GetType(className);
var result = context.Get(t, id);

Now I need to get values of properties from result object. Is there any way to do this by reflection? All I got is the class name and assembly. When I try to get property which belongs to class "TestClass" I get an error because it doesn't belong to "object" type.





Identify Func<> parameter in method using reflection

I have a collection of methods, and I'd like to identify any that contain a Func<(,,,)> parameter (ideally through reflection).

This would be simple enough by tagging such parameters with [IsFuncAttribute], but I'd like to avoid that approach if possible.

For example, if I had the following method, how could I reliably determine that the third parameter is a Func<,>?

public T MyMethod<T>(T param1, bool param2, Func<t,bool> param3)
{
    // do something
}

Alternatively, being able to identify the third parameter as a delegate with a non void return type would be equally useful.





How to retrieve some resources from external JAR file using reflections

Ok, I know that similar questions have been already posted here, and in fact, my solution is feeding from them.

The idea I have is to have some modules (a module is a set of XML files in a folder inside a JAR file) that can be added to an application by the user. That means that the user can put some jars in a predefined folder, and all resources from this JARs must be available for the application. For this purpose, I need to load all JARs from an external folder, and retrieve the XMLs as resources. The JAR files, usually have not any class file, but maybe at the future can have it.

Also the application has a "default" module that is already inside its resources folder. This module is working fine and I can list all XMLs inside it using Reflections.

My code from retrieving all XML files using Reflection is very simple:

    final Set<String> resources = new Reflections(CustomPath.MODULES_FOLDER, new ResourcesScanner()).getResources(Pattern
            .compile(".*\\.xml"));

that returns a Set of strings similar to modules_folder/module_name/file1.xml.

And the code to load a Jar file is using a URLClassLoader:

Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
        method.setAccessible(true); // promote the method to public access.
        method.invoke(loader, new Object[] { url });

As far as I have understood, the resources are available from the URLClassLoader. In fact, I can do something like:

URLClassLoader.getSystemResource("modules_folder/module_name/file1.xml").

And the file is loaded and If I put an invalid path, an error is thrown. Also I need to know the 'module_name' that is not predefined. Then is not a solution.

If I run again the method to retrieve the resources using Reflection, it is only retrieving the files inside the resources folder of the project. No resource from the JAR is retrieved.

Then, I cannot understand why reflections is unable to get the files from the JAR files if are already loaded. I am not sure if Reflections is unable to access to the URLCLassLoader for any reason, or that must be used in a different way.

The question is... Why Reflections is not able to access to the resources from a JAR loaded at runtime? And if it is a limitation, what is the best approach to do it without any Java classes inside the external JAR file?





Java reflection package static final

Before you read this: I know that the following is a pretty nasty piece of code. I am ashamed of it and will eliminate it as soon as possible but for the time beeing I need to make it work.

In my project (project A) I depend on another project (project B) which is imported via gradle from jcenter.

somewhere in project B there is this class

public class Postfixer{
    static final string postfix = " bad postfix";
    postfix(String input){
        input += postfix;
        /*do something with input*/
    }
}

in project A there ist this functioncall

/*do something*/
System.out.println(new Postfixer().postfix("Hello there"));
/*do even more*/

I really have to replace the postfix before /*do something with input*/

So I did the following

Field postfixField = Postfixer.class.getDeclaredField("postfix");
postfixField .setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(postfixField, field.getModifiers() & ~Modifier.FINAL);
postfixField.set(null, " better postfix");

It seems to have worked, when i run the code there is no exception at all but the execution of Postfixer is not affected at all. The output of System.out.println(new Postfixer().postfix("Hello there")); is still "Hello there bad postfix"

Do you see any mistake that i could have made? PS: This is horribly simplified. Nearly all of the code I am trying to change is in the form of binaries and all of this happens deep deep down in the callstack far from my own code.





ReflectionProperty constructor

I'll be grateful (and wiser at the same time ;) ) if anyone can explain me below behavior:

We've got a class.

class Test {
    public $id;
    private $name;
    protected $color;
}

And we've got ReflectionProperty constructor behavior that I do not fully understand.

Working one first:

function check() {
    $class = new Test();
    $ref = new ReflectionObject($class);
    $pros = $ref->getProperties();
    foreach ($pros as $pro) {
        false && $pro = new ReflectionProperty();
        print_r($pro);
    }
}

This will give correct output of:

ReflectionProperty Object
(
    [name] => id
    [class] => Test
)
ReflectionProperty Object
(
    [name] => name
    [class] => Test
)
ReflectionProperty Object
(
    [name] => color
    [class] => Test
)

Now: if I remove "false" from this line:

false && $pro = new ReflectionProperty();

the output will be:

PHP Fatal error:  Uncaught ArgumentCountError: ReflectionProperty::__construct() expects exactly 2 parameters, 0 given

ReflectionProperty::__construct() takes ($class, $name)

The question therefore is: why 'false' even works in the first place?





mercredi 21 août 2019

Assembly.LoadFrom in C# is quick in the debugger, but very slow when deployed

As part of one of our products, we have a dynamically loaded plugin architecture which loads assemblies from a directory.

The system uses Assembly.LoadFrom to load the DLL from the path, and when running inside VS with the debugger attached, the LoadFrom operation is very quick.

When we deploy the application however, the LoadFrom operation takes upwards of 10 seconds to load each Assembly object, which is cripplingly slow as we need to load the Assembly object to check whether it is derived from the base plugin class.

Is there any known reason why loading a DLL in this way should be so much slower when running outside of the IDE?





Can't create an instance of Attribute for a unit test

I am using an API that has a method that fetches some data from a remote server. The method usage is like this:

Attribute a = obj.getRemoteAttribute();

The Attribute class is like this

package a.package.outside.my.project;

import java.util.Date;

public class Attribute {
  private String id;
  private String name;
  private Date modifiedAt;
  private String metadata;

  Attribute(String id, String name, Date modifiedAt, String metadata) {
    this.id = id;
    this.name = name;
    this.modifiedAt = modifiedAt;
    this.metadata = metadata;
  }

  public String getId() {
    return id;
  }

  public Date getModifiedAt() {
    return modifiedAt;
  }

  public String getMetadata() {
    return metadata;
  }

  public String getName() {
    return name;
  }
}

I'm trying to create a unit test, mocking this method. I'm with Mockito for that. The test is something like this:

    @Test
    public void getAttributeShouldWork() throws Exception {
        Storage mockStorage = Mockito.mock(Storage.class);
        Attribute attribute = new Attribute("fake", "fakeName", new SimpleDateFormat("dd/MM/yyyy").parse("21/08/2019"), "fake Metadata"); 
        Mockito.when(storage.getAttribute()).thenReturn(attribute);
        // some other stuff
    }

However, the test does not compile - the constructor from Attribute (4º line) is package private and I can't use it in the test. I can't also extend the class - there is no default constructor. There is no factory to create Attribute, no accessible builder class. I also can't change Attribute's code.

So, my question is - how can I create a fake object to use in this test with mocks? I don't want my unit tests depending on network or remote server's availability...





Scanning Java classes in main project from library

I've creted a Java Library that uses reflection to scan classes based on a filter (base package name). This library only contains the scanning logic, because the idea is to import it into several projects that have the same structure (package structure). I'm using ClassPathScanningCandidateComponentProvider, this is the implementation:

ClassPathScanningCandidateComponentProvider classScanner = new ClassPathScanningCandidateComponentProvider(false);
classScanner.addIncludeFilter(new AnnotationTypeFilter(ProductApi.class));
List<PathsMapper> pathsMappers = new ArrayList();
Iterator var3 = classScanner.findCandidateComponents("com.api.v3.apis").iterator();

I've tested this code within a project and it works perfectly, but if I extract it to a library and then import it to any of the project, it doesn't scan the classes, I don't receive any error message or similar.

How can I specify that the scan must be in the project that imported the library? Is there any other approach better than this?





How to use Scala annotations in Java code

Is there any way to use annotations defined in Scala so they can work with Java code? I have a library with some annotations I would like to use in Java





create instance by full name in Python

I had 2 class with the same name in different folders. I want to get instance by their name. How can I do? Folders as:

folderA/User.py  
folderB/User.py

Both User.py define a class named User. Firstly, I want import both class User in one file, say mymain.py . Secondly, I want create 2 instances by name string. I tried:

  1. in both folderA/__init__.py add line:

    from . import User

  2. in mymain.py add line:

    import User
    construct1 = globals("folderA.User.User")

    construct2 = globals("folderB.User.User")

won't work.Is there any way for me?





Is there a way for a class to access fields in classes that inherit from it using reflection?

What I'm trying to do is have a class that I can inherit from and be able to track changes to properties.

I have this base class called TrackedEntity.

I then create another class TestEntity that inherits from TrackedEntity.

On my TestEntity class I have marked one of my fields with an attribute that I called CompareValues.

TrackedEntity

  public class TrackedEntity {
        public void GetCompareValues<T> () {

            var type = typeof (T);
            var properties = type.GetProperties ();

            foreach (var property in properties) {

              var attribute = (CompareValues[]) property.GetCustomAttributes 
                                             (typeof(CompareValues), false);

              var hasAttribute = Attribute.IsDefined (property, typeof 
                                   (CompareValues));

            }
        }
    }

TestEntity

public class TestEntity : TrackedEntity
    {
        public int one { get; set; }
        [CompareValues]
        public int two { get; set; }
        public int three { get; set; }
    }

CompareValues attribute:

 [AttributeUsage ( AttributeTargets.Property | 
                      AttributeTargets.Field,
                      Inherited = true)]
    public class CompareValues : Attribute {
        public CompareValues () { }
    }

I can then do this

var test  = new TestEntity ();
test.GetCompareValues<TestEntity> ();

In my GetCompareValues method I can find which fields in TestEntity use my CompareValues attribute.

I am trying to find a way to access the value of the fields that have the CompareValues attribute so that I can track the changes and log information about it.

Thank you.





c# reflection: load assembly and replace class

I'd like to dynamically load a c# dll into my program and replace a class in the loaded dll. Is this possible?

The loading of the dll and the instantiating of the class (from the dll) are at two different locations and I don't want to change the instantiating class.

My first idea was to handle the AppDomain.TypeResolve event. But it's never triggered. If I don't load the dll in AppDomain.AssemblyResolve I get an exception. If I do so AppDomain.TypeResolve is not triggered.

As I already said I don't want to change the code that is using the dll. I want to inject another class without the caller noticing (in the best case)





How to initialize a List

TL;DR
I'm stuck with initializing my List<T>s and elements using reflection.

Description
I'm trying to initialize my whole export class programmatically using reflection.
This class contains a lot sub classes and lists.

The purpose of this function is to quickly generate a filled class for XML export.
And why am I using reflection, you may ask, that's because of the fact that I have a lot of different classes of the huge kind.
It would be a pain in the ass to write them all out just for testing purpose.

Code

public static object Populate(object object_Orginal)
{
    PropertyInfo[] PropertyInfos = object_Orginal.GetType().GetProperties();

    for (int iIndex = 0; iIndex < PropertyInfos.Length; iIndex++)
    {
        PropertyInfo PropertyInfo_Tmp = PropertyInfos[iIndex];

        if (PropertyInfo_Tmp.GetSetMethod() == null)
        {
            continue;
        }
        // Is it right to exclude them?
        if (PropertyInfo_Tmp.Name == "Capacity" || PropertyInfo_Tmp.Name == "Count")
        {
            continue;
        }
        Type Type_Tmp = PropertyInfo_Tmp.PropertyType;

        if (Type_Tmp == typeof(int))
        {
            PropertyInfo_Tmp.SetValue(object_Orginal, 1);
        }
        // [...] a few more basic types

        // >>> Here I'm completly stuck - and yea it's a mess
        else if (Type_Tmp.Name == "List`1") // typeof(List<>))
        {
            object list = Activator.CreateInstance(Type_Tmp);

            MethodInfo add = Type_Tmp.GetMethod("Add");

            IEnumerable<Attribute> a = PropertyInfo_Tmp.GetCustomAttributes();

            PropertyInfo[] propertyInfo = list.GetType().GetProperties();
            foreach (PropertyInfo property in propertyInfo)
            {
                object d = Populate(property);
                property.SetValue(list, d);
            }

            //foreach (Attribute item in a)
            //{
            //    add.Invoke(list, new object[] { Populate(item) });
            //}

            //add.Invoke(list, new[] { item });
            //prop.SetValue(x, list, null); 

        }
        // <<<

        else
        {
            ConstructorInfo ConstructorInfo_Property = Type_Tmp.GetConstructor(Type.EmptyTypes);
            object object_Property = ConstructorInfo_Property.Invoke(new object[0]);
            object_Property = Populate(object_Property);
            PropertyInfo_Tmp.SetValue(object_Orginal, object_Property);
        }
    }
    return object_Orginal;
}

Original code from here

I tried a few different ways but can't implement them right.
The primary goal is to initialize the List<T> and then add one - more items to the list and initialize them recursively.





Get field names of a class in Java

I am trying to generate a CSV mapping for the fields of a class in Java in an automatic way since I need to use it several times.

I have the following method for trying to get the field names: (where CSV header is something like "DB_NAME|FIELD_NAME|ADDITIONAL_F1|ADDITIONAL_F1")

public static String generateCsvAttributesMapping(Class<WhateverClassName> model) {

    StringBuilder csvBuilder = new StringBuilder(CSV_HEADER);

    Field[] fieldList = model.getDeclaredFields();
    for (Field field : fieldList) {
        field.setAccessible(true);
        csvBuilder.append(field.getName().replaceAll("(.)(\\p{Upper})", "$1_$2").toUpperCase());
        csvBuilder.append("|");
        csvBuilder.append(field.getName());
        csvBuilder.append("||\n");
    }
   return formatOutput(csvBuilder.toString());
}

and a test call like:

@Test
public void testGenerationWithObject() {
    log.info(CsvAttributesMappingGenerator.generateCsvAttributesMapping(WhateverClassName.class));
}

The output should have multiple rows like FIELD_NAME|fieldName|| where the camel cased item should be collected from the given class. I attempted to use Java Reflection API as I have seen on several examples but I get a strange String output instead. (not the serialized @randomCharsLikeName). Tried toString() and other dirty tricks but nothing worked.

Can someone tip me up a little with this? Or at least tell me if it is possible to do what I tried? Thanks in advane!





How exactly is "interacting with Core.Compiler" undefined in a generated function?

The docs for generated functions at some point say the following:

Some operations that should not be attempted include:

  1. ...

  2. Interacting with the contents or methods of Core.Compiler in any way.

What exactly is meant by "interacting" in this context? Is just using things from Core.Compiler from within a generated function undefined behaviour?

My use case is to detect builtin functions from within an IRTools dynamo (which constructs generated functions), but you can refer to the following dummy code (inspired by Cassette.canrecurse), which contains the actual "interactions" I want to perform:

julia> @generated function foo(f, args...)
           mod = Core.Compiler.typename(f).module
           is_builtin = ((f <: Core.Builtin) && !(mod === Core.Compiler))
           if is_builtin
               quote
                   println("$f is builtin")
                   f(args...)
               end
           else
               :(f(args...))
           end
       end

foo (generic function with 1 method)

julia> foo(+, 1, 2)
3

julia> foo(Core.tuple, 1, 2)
tuple is builtin
(1, 2)

Which seems to work without problems.





mardi 20 août 2019

Avoiding $GLOBAL state in PHP with dependancy injection?

I have encountered a situation where I would like to avoid using $GLOBAL state, but cannot workout how to do so. I believe Reflection and Dependancy injection could solve this:

Here is a contrived example (Yes I know its a little bent...); Say we have a Calculator class and helper functions that basically replicate its functionality e.g. add, subtract. Now we also want a history of our calculations to be accessible.

How can I use these helper functions without having to manually insert the Calculator as a dependancy?

class Calculator
{
    private $history = [];

    public function add(int $a, int $b): int
    {
        $result = $a + $b;

        $this->history[] = $result;

        return $result;
    }

    public function subtract(int $a, int $b): int
    {
        $result = $a - $b;

        $this->history[] = $result;

        return $result;
    }

    public function history(): array
    {
        return $this->history;
    }
}

function add(int $a, int $b): int
{
    $calculator = new Calculator;
    return $calculator->add($a, $b);
}

function subtract(int $a, int $b): int
{
    $calculator = new Calculator;
    return $calculator->subtract($a, $b);
}

function history(): array
{
    $calculator = new Calculator;
    return $calculator->history(); // Clearly this will be empty
}

See what I mean? Currently calling history() will of course return an empty array...

Of course this would work:

function add(Calculator $calculator, int $a, int $b): int
{
    return $calculator->add($a, $b);
}

function history(Calculator $calculator): array
{
    return $calculator->history();
}

Although if i use this as a package its very error prone, labour intensive to manually wire up these dependancies... let alone every time I call a helper function.

Another method that would work is globals:

$GLOBALS['calculator'] = new Calculator;

function add(int $a, int $b): int
{
    return $GLOBALS['calculator']->add($a, $b);
}

function history(): array
{
    return $GLOBALS['calculator']->history();
}

Although ... yuk yuk yuk. No thank you.

HELP!





Net Core: Place StartsWith into Expression Method Info to not Receive Ambiguity Error

How do I place this method into an expression builder safely? First parameter is string, second parameter is enum.System.StringComparison. The second enum parameter is giving error.

return persons.Where(p => p.Name.StartsWith(filterModel.Term, StringComparison.InvariantCultureIgnoreCase))  

Eventually want to place this into a method builder, and its giving error below.

MethodInfo startsWith = typeof(string).GetMethod("StartsWith", new[] { typeof(string), typeof(enum(string)) });

public class Person
{
    public String Name { get; set; }
    public DateTime DOB { get; set; }
    public String Email { get; set; }
}

Resources:

C# Reflection typeof(string).GetMethod("Equals) Ambiguous match on netcoreapp2.2

GetProperty reflection results in "Ambiguous match found" on new property





Create assembly that when referenced it prevents a program from using Main entry method

I want to perform the same behavior that NUnit tests perform that it prevents using a Main method. In this case the error that I need is a good thing. Let me explain what I mean.

  1. I create a hello world application targeting the .net core

Project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>



</Project>

Code file: (default hello world c# code)

  1. If I then run that application it runs fine

  2. Add a reference to NUnit and my project file now contains.

.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NUnit" Version="3.12.0" />
    <PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
  </ItemGroup>

</Project>

  1. When I try to compile the project I get the error:

Error CS0017 Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.

That means that there is another Main method. That method is probably located on the NUnit nuget package I am referencing. This is the error I am trying to replicate!.


Now this is how I try to replicate the same error:

  1. I remove the NUnit nugget package having no references to NUnit on my hello world application.

  2. Create a Project ClassLibrary1 with the following code:

    public class MyLib { static void Main() { Console.WriteLine("fooooo"); // do something } }

  3. Have my hello world application reference that project:

enter image description here

When I compile I get no errors even though there are 2 Main methods!

How does NUnit manages to prevent using a Main method? How can I replicate the same behavior? I want to create an assembly that when referenced it prevents executing the Main method.





How to define new annotations for public methods in class via Byte Buddy

I'm trying to annotate all public methods in my class annotated with my custom annotation using Byte Buddy.

I've already tried to use the code from the comment here: Add method annotation at runtime with Byte Buddy

Java version: 1.8. The app is for testing microservices. Application is running via Spring Boot. I try to annotate all needed methods in my app with annotation with value depending on method name.

            <dependency>
                <groupId>org.reflections</groupId>
                <artifactId>reflections</artifactId>
                <version>0.9.11</version>
            </dependency>
            <dependency>
                <groupId>net.bytebuddy</groupId>
                <artifactId>byte-buddy</artifactId>
                <version>1.10.1</version>
            </dependency>
            <dependency>
                <groupId>net.bytebuddy</groupId>
                <artifactId>byte-buddy-agent</artifactId>
                <version>1.10.1</version>
            </dependency>  


Working method:


import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import io.qameta.allure.Step;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.MemberAttributeExtension;
import net.bytebuddy.description.annotation.AnnotationDescription;
import net.bytebuddy.matcher.ElementMatchers;
import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;

public class StackOverflowExample {

    private static final String REGEX = "some-package";

    public void configureAnnotation() {
        Reflections reflections = getReflections();
        Set<Class<?>> allClasses = reflections.getSubTypesOf(Object.class);
        allClasses.forEach(clazz -> {
            if (clazz.isAnnotationPresent(ConfigureSteps.class)) {
                List<Method> publicMethods = Arrays.stream(clazz.getDeclaredMethods())
                                                   .filter(method -> Modifier.isPublic(method.getModifiers()))
                                                   .collect(Collectors.toList());
                AnnotationDescription annotationDescription = AnnotationDescription.Builder.ofType(Step.class)
                                                                                           .define("value", "new annotation")
                                                                                           .build();
                publicMethods.forEach(method -> new ByteBuddy().redefine(clazz)
                                                               .visit(new MemberAttributeExtension.ForMethod()
                                                                              .annotateMethod(annotationDescription)
                                                                              .on(ElementMatchers.anyOf(method)))
                                                               .make());
            }
        });
    }

    private Reflections getReflections() {
        return new Reflections(new ConfigurationBuilder().setScanners(new SubTypesScanner(false), new ResourcesScanner())
                                                         .addUrls(ClasspathHelper.forJavaClassPath())
                                                         .filterInputsBy(new FilterBuilder().include(REGEX)));
    }
}

I call configureAnnotation method before all the tests using JUnit @BeforeAll annotation. Method is invoked without issues but methods in my class with ConfigureSteps annotation aren't annotated with Step annotation. What is the problem? Or may be I should build Agent like it is in tutorial here: http://bytebuddy.net/#/tutorial And in this case what way should I override transform method?





What is the purpose of access modifiers if they can be bypassed with reflection?

I understand that using access modifiers is an important practice when writing Java (or most) code, but isn't it effectively made redundant by the fact that you can bypass these modifiers using reflection?

For example, if I want to protect my objects sensitive variables by setting them to private and providing accessor methods, someone can still easily come in and bypass this using reflection, and potentially set unsafe values. Why does Java provide access modifiers, and then a tool to bypass them? It seems it would just be easier to not use either.





Could not invoke method: java.lang.IllegalArgumentException: argument type mismatch

I am trying to invoke a method through reflection on an EJB that has been looked up through its JNDI reference. It requires three arguments: a EndUser object (custom object), a Set (custom class) and a boolean. The first object causes the invocation to fail with a "Could not invoke method: java.lang.IllegalArgumentException: argument type mismatch". This occurs as long as the first argument is non-null. Setting it to null makes the error go away.

The actual call:

  public Relation createRelation(final Relation relation, final HashSet<Contact> contacts) {
        final EndUser user = new EndUser();
        Object[] args = new Object[]{user, contacts, false};

        try {
            return (Relation) EjbUtils.invoke("registerEndUser", REGISTRATION_SERVICE_JNDI, args);
        } catch (final Throwable throwable) {
            LOGGER.error("Could not invoke method", throwable);

            return null;
        }
}

The EjbUtils method:

 public static Object invoke(final String methodName, final String ejbName, final Object... args) throws Throwable {
        final String jndiName = getEjbJndi(ejbName);
        final Object remoteObject = lookup(jndiName);
        final Method[] methods = remoteObject.getClass().getMethods();

        for (final Method method : methods) {
            if (methodName.equals(method.getName()) && args.length == method.getParameterCount()) {
                try {
                    return method.invoke(remoteObject, args);
                } catch (IllegalAccessException e) {
                    final String message = String.format("Could not invoke method %s on %s: %s", methodName, ejbName, e.getMessage());
                    LOGGER.error(message);
                    throw new IllegalStateException(message, e);
                } catch (InvocationTargetException e) {
                    throw e.getCause();
                }
            }
        }

        throw new IllegalArgumentException("Method not found");
    }

The method I am trying to invoke:

    public Relation registerEndUser(final EndUser relation, final Set<Contact> contacts, boolean sendMail)
            throws RegistrationServiceException, RegistrationServiceWarning {
        return registerRelation(relation, contacts, sendMail);
    }

The weird part is: if I replace

final EndUser user = new EndUser();

with

final EndUser user = null;

No exception is thrown and the method is invoked, which should indicate the arguments are of the correct type.

When debugging I can see the correct method is found, and the required parameter types are identical to the ones I provide.





ReflectionIt pagination generates empty hrefs

Asp.Net Core 2.2 using ReflectionIT.Mvc.Paging 3.5.0. Generated View has empty pagination hrefs. How to solve this?

Controller:

public async Task<IActionResult> Index(int page = 1, string sortExpression = "-LastUpdated")
{
  var qry = _context.Invoice.AsNoTracking();
  var model = await PagingList.CreateAsync(qry, 10, page, sortExpression, "-LastUpdated");
  return View(model);
}

View:

@model ReflectionIT.Mvc.Paging.PagingList<Admin.Models.Person>
@using ReflectionIT.Mvc.Paging
@addTagHelper *, ReflectionIT.Mvc.Paging

<nav aria-label="Person navigation">
  @await this.Component.InvokeAsync("Pager", new { pagingList = this.Model })
</nav>

<table class="table table-striped">
 <thead>
    <tr>
        <th>
            @Html.SortableHeaderFor(model => model.Name)
        </th>
        ...
        <th>
            @Html.SortableHeaderFor(model => model.LastUpdated)
        </th>
 </thead>
 ...
</table>

Generated pagination:

<nav aria-label="Person navigation">
  <ul class="pagination">
     <li class="active">
         <a href="">1</a>
     </li>
     <li>
         <a href="">2</a>
     </li>
     ...
  </ul>
</nav>

Generated code uses glyphicon, which is not supported in Bootstrap 4. Perhaps a wrong version the package? Thanks for any help!





Is there a way to use Expressions to get data from models for SQLite.net query?

I am saving a large amount of data that was received as models to various tables in a SQLite.net database. I currently have 15 methods for each DB type which are all in an identical format. I am trying to write a method using reflection which allows me to pass in expressions which retrieve the data from the model and data base object (dbo) which compiles fine but the model data is unable to be compiled to SQL.

The exception i receive is "Cannot compile: Parameter".

I have tried various formats of this code, including a combination of Expressions and Func set ups, separating the model from the SQLite query and getting the ID before in its own expression, however i believe that everything is being compiled together regardless.

This is an example of 1 of the 15 methods that are called for each model type. I want to replace this with 1 method that can save all types for me

private async Task SaveDevelopments(List<DevelopmentsModel> developmentModels)
{
    var toInsert = new List<DevelopmentsDBO>();
    var toUpdate = new List<DevelopmentsDBO>();

    foreach (var developmentModel in developmentModels)
    {
        var developmentDBO = await DatabaseHelpers.Table<DevelopmentsDBO>().Where(d => d.DevelopmentID == developmentModel.DevelopmentID).FirstOrDefaultAsync();
        if (developmentDBO == null)
        {
            developmentDBO = new DevelopmentsDBO();
            ModelFactory.UpdateFromModel(developmentDBO, developmentModel);
            toInsert.Add(developmentDBO);
        }
        else
        {
            ModelFactory.UpdateFromModel(developmentDBO, developmentModel);
            toUpdate.Add(developmentDBO);
        }
    }

    await DatabaseHelpers.InsertAllAsync(toInsert);
    await DatabaseHelpers.UpdateAllAsync(toUpdate);
}

This was attempt 1 at using reflection and expressions to replace all 15 methods with a shared method

await SaveModels<DevelopmentDBO, DevelopmentsModel>(data.DevelopmentModels, (dbo, model) => dbo.DevelopmentID == model.DevelopmentID);

private async Task SaveModels<DBO, Model>(List<Model> models, Func<Model, DBO, bool> findSelf) where DBO : new()
{
    var toInsert = new List<DBO>();
    var toUpdate = new List<DBO>();

    foreach (var model in models)
    {
        var dbo = await DatabaseHelpers.Table<DBO>().Where(x => findSelf.Invoke(x, model)).FirstOrDefaultAsync();
        if (dbo == null)
        {
            dbo = (DBO)Activator.CreateInstance(typeof(DBO));
            ModelFactory.UpdateFromModel(dbo, model);
            toInsert.Add(dbo);
        }
        else
        {
            ModelFactory.UpdateFromModel(dbo, model);
            toUpdate.Add(dbo);
        }
    }

    await DatabaseHelpers.InsertAllAsync(toInsert);
    await DatabaseHelpers.UpdateAllAsync(toUpdate);
}

This was attempt 2

await SaveModels<DevelopmentDBO, DevelopmentsModel>(data.DevelopmentModels, x => x.DevelopmentID, x => x.DevelopmentID);

private async Task SaveModels<DBO, Model>(List<Model> models, Func<Model, Guid> findModelID, Expression<Func<DBO, Guid>> findDBOID) where DBO : new()
{
    var toInsert = new List<DBO>();
    var toUpdate = new List<DBO>();

    foreach (var model in models)
    {
        Guid modelID = findModelID.Invoke(model);

        Expression<Func<DBO, bool>> findSelf = x => findDBOID.Compile().Invoke(x) == modelID;

        var dbo = await DatabaseHelpers.Table<DBO>().Where(findSelf).FirstOrDefaultAsync();
        if (dbo == null)
        {
            dbo = (DBO)Activator.CreateInstance(typeof(DBO));
            ModelFactory.UpdateFromModel(dbo, model);
            toInsert.Add(dbo);
        }
        else
        {
            ModelFactory.UpdateFromModel(dbo, model);
            toUpdate.Add(dbo);
        }
    }

    await DatabaseHelpers.InsertAllAsync(toInsert);
    await DatabaseHelpers.UpdateAllAsync(toUpdate);
}

My goal as above is to make a method that I can use to replace 15 nearly identical methods that save each type of DBO. I am not keen on using SQL in string format as this is difficult to read for future developers and easy to make mistakes.

Is there another way of doing this that I'm not aware of?





lundi 19 août 2019

MemberExpression is marked as Convert(...) call instead of MemberExpression

I'm currently facing an issue with using Reflection on custom types. I have a method with the following signature:

protected static bool ReplacePropertyValue<TTargetResource, TValue>(TEntity entity, TResourcePatch resourcePatch, Expression<Func<TResource, TTargetResource>> sourceResourcePropertyExpression, Expression<Func<TTargetResource, TValue>> sourcePropertyExpression, Expression<Func<TEntity, TValue>> targetPropertyExpression)

where TEntity is the database-entity I want to update. where TTargetResource is the resource of the patch-document I want the new value from. where TValue is the type of the property I want the new value from to be set in the entity.

resourcePatch contains all the patch-instructions I want to apply to the entity. sourceResourcePropertyExpression is the expression for the resource with the new/changed value. sourcePropertyExpression is the expression to the resource's property with the new/changed value. targetPropertyExpression is the expression pointing to the property which should have the new/changed value.

However I am facing an issue where the targetPropertyExpression is not a MemberExpression. Below is the call of the method

 ReplacePropertyValue(theEntity, resourcePatch, team => team.ParentTeam, pt => pt.Id, team => team.TeamParentTeamId)

However, the last param is shown as {team => Convert(team.TeamParentTeamId)} and I don't get the point why. TeamParentTeamId is of type Guid. When used with another property of type Guid? it works as expected.

Can anyone tell me why the first one (Guid) is a Convert(...)-expression?





How to swap the method bodies of two functions

I'm in the process of writing some auto generating code based from (not on) existing code using reflection. If I can give a scenario think of it as what Im doing as writing a VS extension that will convert Winforms to XAML.
Now I've gotten to the point where I need to be able to copy the method bodies. Reason being the "ItemClick" events signatures are slightly different and I cannot just assign it from Winforms to XAML. I am able to generate the signature. But how do I go about copying the method bodies across? Remember the purpose of it all is to in the end generate C# code (as I have literally hundreds of files I need to convert).





Get Generic Type using Reflection

class Things{   
  Thing<Vegetables> veggies;
  Thing<Fruits> fruits;

   public Things(String name,
                Class<V> type) {
    this.name = name;
    this.valueClass = type;
}
....
}

Using reflection I want to create an object for each field in this class and set them. But I cant get and set the type, here is my code:

  Field[] allFields = Things.class.getDeclaredFields();
    for (Field field : allFields) {
            Thing thing =  new Thing(field.getName(),field.getGenericType().getTypeName().getClass());       
    }
}

field.getGenericType().getTypeName().getClass()

Returns String and not Vegetables or Fruits (Rightly so) How can I get the generic type of the field using Reflection?

Note: The so called dublicate question is not answering or asking the same thing





C# custom attribute hoe to change target class propter

I'm try to find a solution to realize decrypt/encrypt when access a class property by get/set.

I had researched something about C# custom attribute, but seemimgly it can't work, so I want to know whether it's impossible to change the class property by attribute.

    [AttributeUsage(AttributeTargets.Property)]
    public class MyAttribute : Attribute
    {
        // How to change the tragetClass.Name when access by get/set
    }

    public class TargetClass
    {
        [MyAttribute]
        public string Name { get; set; }
    }





Dynamically assigning properties to ExpandoObject

I need to dynamically add properties with values to an anonymous object so I am using the ExpandoObject with a dynamic variable. However, I don't know the property names before runtime and I don't want to hard code many properties using routeValues.MyProp = "value" for different scenarios. It turns out the ExpandoObject doesn't like using indexers of the form routeValues[prop.Name] = value;as it causes this error:

enter image description here

This is the method:

public object GetRouteValues() {
    var properties = GetType().BaseType.GetProperties();
    dynamic routeValues = new ExpandoObject();

    foreach (var prop in properties)
    {
        var value = prop.GetValue(this) as string;

        if (!string.IsNullOrWhiteSpace(value))
            routeValues[prop.Name] = value; // causes error
    }

    return routeValues;
}

How can I dynamically add properties whose name I don't know until runtime to a dynamic object? Thanks.





dimanche 18 août 2019

How to pass an string as a type parameter for a generic DbSet in Entity Framework?

Consider the following sample code, What's the most concise way to pass C# generic type as a parameter?

public dynamic MyDbSet(string typeName)
{
    var typeofDbSet = typeof(DbSet<>);
    Type[] typeArgs = { Type.GetType(typeName) };
    var type = typeofDbSet.MakeGenericType(typeArgs);
    dynamic dbsetOfT = Activator.CreateInstance(type);

    return dbsetOfT;

    //Call it
    //var notificationTypes = MyDbSet("NotificationType");
    //var list = notificationTypes.ToList();
}

Or something like this:

public dynamic MyDbSet2(string typeName)
{
    var keyValuePairs = new Dictionary<string, dynamic>
    {
        {nameof(NotificationType), Set<NotificationType>().AsQueryable()}
    };

    return keyValuePairs[typeName];
    //Call it
    //var notificationTypes = MyDbSet2("NotificationType");
    //var list = notificationTypes.ToList();
}





Calling a generic method using reflection and casting correctly

I am trying to call a generic method using reflection; however I would like to know the actual type of the generic parameter within the method.

Here's the generic function I am calling

public object Get<T>() 
    {
      string typeName = typeof(T).Name;
      if (instanceManager.ContainsKey(typeName))
      {
        return instanceManager[typeName];
      }
      else
      {
        T Tinstance = (T)Activator.CreateInstance(typeof(T));
        instanceManager.Add(typeName, Tinstance);
        return Tinstance;
      }
    }

Where instanceManager is just a dictionary

Dictionary<string, object> instanceManager;

When I call this method via reflection using the code below

public static object InvokeGenericMethod(Type sourceType, string methodName, Type parameterType, object[] inputParams, object invokeOn = null)
    {
      MethodInfo methodInfo = sourceType.GetMethods().Where(item => item.IsGenericMethod).First();
      MethodInfo genericMethod = methodInfo.MakeGenericMethod(parameterType);
      object obj = genericMethod.Invoke(invokeOn, inputParams);
      return obj;
    }

The method gets called as expected, however the typeof(T) is just System.RuntimeType rather than the actual type of the generic parameter. Is there a way to retrieve the actual type name of T within the method Get() ?





Profile an application and check if reflection is used

I would like to profile my application, and check if any part of my code is using reflection, but also if any part of the dotnet core or netstandard framework is using reflection during my application execution and usage.

The purpose of this exercise is to eventually detect reflexion usage at build time, at least reflection that is not put in a cache, but also try to improve the global performances of my webapi.

Thank you





Changing unboxed of primitive typed (e.g. long, not Long) by reflection

I'm trying to change a value of following variable by java reflection: public final static Long DEFAULT_TIMEOUT = 100000L;

There is no exception or errors but value remains.

JDK: Oracle 8 JDK.

There is simple class to reproduce the problem.

package testpackage;

public class LibraryClass {
  // Changing long to Long fixes the issue
  public final static long DEFAULT_TIMEOUT = 100000L; 
}

Simple test-case. I'm using org.apache.commons.lang3.reflect.FieldUtils to remove finale/making the field accessible. I also tried to work with FieldUtils/and class object (because of staticness of the filed= to change value. But every approach failed.

public class FinalStaticVariableChangeCheck {

  private static Logger LOG = LoggerFactory.getLogger(FinalStaticVariableChangeCheck.class);

  @Test
  public void testLChangingLibraryClass()
      throws NoSuchFieldException, IllegalAccessException, InterruptedException, InstantiationException {
    LibraryClass sampleClass = new LibraryClass();
    final Class<?> clazz;
    final Field    field;

    clazz = sampleClass.getClass();
    field = clazz.getDeclaredField("DEFAULT_TIMEOUT");

    FieldUtils.removeFinalModifier(field, true);
    field.set(sampleClass, 1234L);

    LOG.info("Output: " + sampleClass.DEFAULT_TIMEOUT);
    Assert.assertEquals(1234L, sampleClass.DEFAULT_TIMEOUT);


  }

}

The output is 100000.

However, by changing public final static long DEFAULT_TIMEOUT = 100000L; to public final static Long DEFAULT_TIMEOUT = 100000L; solves the problem

Expected: output 1234 and the test-case is not failing.

The issue seems to be related to the unboxed type. Any Ideas how to workaround the problem? Unfortunately the code resides in an external library and my PRs to solve the problem in more elegant way are currently "ignored".





samedi 17 août 2019

Using Qt QMetaObject to print a class name

I'm trying to understand Qt's reflection capabilities by testing its QMetaObject class. As a minimum example, I'm trying to see if I can find the name of a class using using QMetaObject. However, upon running the programme, I get a compile time error "undefined reference to 'vtable for ReflectedClass'". I can remove the compile time error by removing the Q_OBJECT macro however then when printing out the class name I get "QObject" which is the parent class and NOT the class Ive defined. I was told I must add in Q_OBJECT to get the class of the child class. Can anyone help me address the error and help me to simply get a class name using QMetaObject. Here is the code:

#include <QCoreApplication>
#include <iostream>
#include <QString>
#include <QObject>
#include <QMetaObject>
#include <QMetaProperty>
#include <QDebug>

using namespace std;

class ReflectedClass : public QObject {
    Q_OBJECT
public:
    int getFieldA(){
        return fieldA;
    }
    bool getFieldB(){
        return fieldB;
    }
    QString getFieldC(){
        return fieldC;
    }
    void setFieldA(int i){
        fieldA = i;
    }
    void setFieldB(bool b){
        fieldB = b;
    }
    void setFieldC(QString s){
        fieldC = s;
    }

private:
    int fieldA;
    bool fieldB;
    QString fieldC;
};

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    ReflectedClass *a = new ReflectedClass();
    a->setFieldA(3);
    a->setFieldB(true);
    a->setFieldC("Hello");
    const QMetaObject *mo = a->metaObject();
    qDebug() << mo->className();
    return app.exec();
}





Given both types, can I determine if a virtual function have been overridden?

I am designing a system that is built from a collection of modules. The base Module class has a set of virtual functions that do nothing by default, but can be overridden in derived module classes if they are needed.

For example, one of these functions is OnUpdate(). Currently when an update occurs, I loop through all modules and run this function on each of them. Of course, this results in many "wasted" calls on any module that does not override the relevant function.

Given that most modules do not override most member functions (and profiling indicates that this is a bottleneck in my system), what I'd prefer to do is keep track of which modules DO override a member function and execute only those. At the moment, I am planning to keep an extra vector of only those module pointers that need to be run.

My problem is that collecting this information requires me to detect whether or not a module has overridden each member function. I can do this analysis on module creation when I know the exact derived type that I'm working with, so I think it should be possible, but the test that I expected to work does not.

Here's some simplified detection code that fails:

    template <typename T>
    T & AddModule() {
      static_assert(std::is_base_of<Module, T>,
                    "AddModule() can only take module types.");

      // Create the new module and store it.
      auto mod_ptr = std::make_shared<T>();
      modules.push_back(mod_ptr);

      // If the module has OnUpdate() track it!
      // *** This test is not working! ***
      if (&T::OnUpdate != &Module::OnUpdate) {
        on_update_mods.push_back(mod_ptr);
      }

      // ...lots more tests here...

      return *mod_ptr;
    }

Is there some other way that I can handle this detection?

I'm also happy to hear alternate ideas for how to achieve my goal. I definitely want to keep it easy for module writers to simply implement any of the designated functions and have them called as appropriate.

The only other option I've come up with so far is to NOT have the virtual functions in the Module base class and then use SFINAE to detect them in the derived class, followed by wrapping them in lambdas and storing a vector of functors to run. I think that will work BUT it will be slightly slower (more indirection with the functors) and more error prone (right now if you make a typo in a member function name the override keyword will throw an error...)

Thanks in advance for any other suggestions.





Working with generics to store a method execution

I am trying to learn a bit of what I consider more complex Java, I got interested in Generics as I noticed it can do amazing things. I thought about doing this: Have a Map that will store a class and some form of method, this would be used so in case of giving a certain class, lets say String.class it would run the code inside the method.

I saw it being done and working on a project called ACF (Aikar command framework).

An example of how it manages to register the new method:

registerContext(char.class, c -> {
    String s = c.popFirstArg();
    if (s.length() > 1) {
        throw new InvalidCommandArgument(MessageKeys.MUST_BE_MAX_LENGTH, "{max}", String.valueOf(1));
    }
    return s.charAt(0);
});

His register method seems simple being just:

// The map
protected final Map<Class<?>, ContextResolver<?, R>> contextMap = new HashMap<>();
// The register class
public <T> void registerContext(Class<T> context, ContextResolver<T, R> supplier) {
    contextMap.put(context, supplier);
}

I tried making something similar but yet I couldn't really understand. I am whiling to do more research, but at this point I don't know what to search for. I don't know what this type of method storage or method declaration is called. I watched a few videos and read a few posts about the generics in Java but mostly stay very basic which I manage to understand, but still can't figure out how this works. The results I expect is to be able to for example call contextMap.get(class).run() and it would invoke the method.

edit:
PS: I'm not asking anyone to write code for me or do this or that, just to point me in the right direction to learn and I'll do the rest myself. Or maybe some small explanations about generics.





How to access custom list object at runtime

I have the following custom object

public class Events
{
    public int Id { get; set; }
    public DateTime CreateDate { get; set; }
    public string Category { get; set; }
}

It is stored serialized as a List<Events>

[
  {
    "Id": 1,
    "CreateDate": "2019-08-15",
    "Category": "consert"
  },
  {
    "Id": 2,
    "CreateDate": "2019-08-15",
    "Category": "movie"
  },
  {
    "Id": 3,
    "CreateDate": "2019-08-15",
    "Category": "dance"
  }
]

Read/deserialized, using typed variable and linq to access properties/values

List<Events> eventlist = JsonConvert.DeserializeObject<List<Events>>(jsonstring)

var maxid = eventlist.Max(i => i.Id);


I started testing how to use reflection to access an events properties/values.

foreach (var pi in eventlist[0].GetType().GetProperties())
{
    if (pi.CanWrite && pi.CanRead)
    {
        object o = pi.GetValue(itemData, null);
        if (o != null)
        {
            ...
        }
    }
}


If I now also would read/deserialized at runtime, e.g.

var eventlist = JsonConvert.DeserializeObject(jsonstring, eventtype)


How do I, using reflection, get the runtime-created eventlist items, and e.g. find the max id?