lundi 30 septembre 2019

Does C++ 17 has static reflection?

Combining if constexpr with some <type_traits> entities, in C++ 17, I'm able to inspect types on compiler time. Can these techniques be considered static reflection? Example:

if constexpr (std::is_same_v<T, U>) statement

Does the reflection concept applies only to runtime? Is right to say static reflection?





How to get properties of object in python

class ClassB:
    def __init__(self):
        self.b = "b"
        self.__b = "__b"

    @property
    def propertyB(self):
        return "B"

I know getattr,hasattr... can access the property. But why don't have the iterattr or listattr?

Expect result of ClassB object:

{'propertyB': 'B'}

Expect result of ClassB class:

['propertyB']




Golang update struct field inside function passed as interface

I am new to go (golang). That is why my question may be irrelevant (or impossible to answer).

I have created two structs. Both of these embed another struct. Now I want to update a field of the embedded struct inside a function.

package main

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

type Model struct {
    UpdatedAt time.Time
}

type Fruit struct {
    Model
    label string
}

type Animal struct {
    Model
    label string
}

func update(v interface{}) {
    reflectType := reflect.TypeOf(v)
    reflectKind := reflectType.Kind()
    if reflectKind == reflect.Ptr {
        reflectType = reflectType.Elem()
    }
    m := reflect.Zero(reflectType)
    fmt.Println(m)
}

func main() {
    apple := &Fruit{
        label: "Apple",
    }
    tiger := &Animal{
        label: "Tiger",
    }
    update(apple)
    update(tiger)
    fmt.Println(apple)
    fmt.Println(tiger)
}

I wish to implement the update function so that it will put the current time in UpdatedAt of the passed struct. But I am not able to do this.

In this case, the field of Fruit and Animal is same: label. But it will not always be. Please keep that in mind when providing your suggestions.

Any guidance would be much appreciated.





"object is not an instance of declaring class" at calling Method.invoke() with JoinPoint in @Before Spring AOP

I want to call each getter of Argument object of each method of Controller of Spring framework through Spring AOP. But when I call the getter, there is an exception which message is "object is not an instance of declaring class".

What am I wrong ?

Thanks in advance.

@Before("execution(* *(..)) && within(@org.springframework.stereotype.Controller *)")
public void beforeController(JoinPoint joinPoint) {

    MethodSignature methodSignature =  (MethodSignature)joinPoint.getSignature();

    StringBuffer methodFullName = new StringBuffer("");

    Class<?>[] parameters = methodSignature.getParameterTypes();

    for (Class<?> parameter : parameters) {

        methodFullName.append("\t" + parameter.getName() + "\n");

        Method[] methods = parameter.getDeclaredMethods();

        for (Method method : methods) {

            if (method.getName().startsWith("get")) {

                try {

                    Object object = method.invoke(parameter);

                    methodFullName.append("\t\t" + object.toString() + "\n");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    System.out.println(methodFullName.toString());
}




How can I rotate Cubemap?

I am currently working on some reflection shaders in Unity. And I am totally newbie about shaders. I found an article about cubemap rotation. I' ve done some implementation but it seems doesn't work properly. I rotated cubemap in vertex shader with only rotate normal.
How can I achive this effect?

 float3 RotateAroundYInDegrees (float3 vertex, float degrees)
      {
         float alpha = degrees * UNITY_PI / 180.0;
         float sina, cosa;
         sincos(alpha / 2, sina, cosa);
         float3x3 m = float3x3(cosa, 0, sina, 0, 1, 0, -sina, 0, cosa);
        float3 r = float3(mul(m, vertex.xyz) ).rgb;
        return r;
    }
    void vert (inout appdata_full v, out Input o) {
        UNITY_INITIALIZE_OUTPUT(Input,o);
        v.normal = RotateAroundYInDegrees(v.normal, _Rotate);
      }




dimanche 29 septembre 2019

Why I can get a instance of an class that is not referenced in this assembly?

Background: We have three assemblies:

  • printing (Generates reports as pdfs) -> Reference to businessObjects.interfaces

  • businessObjects (contains all of our business objects) -> Reference to businessObjects.interfaces

  • businessObjects.interfaces (Here we declare the properties for the printing, only properties that are needed are included) -> No references

The object is implemented like this:

public interface IDeliveryNote // Assembly: businessObjects.interfaces

public partial class DeliveryNote : IDeliveryNote // Assembly:businessObjects

There is also a class 'Order' inside the DeliveryNote, holding a bool 'IsNeutralDelivery'

Problem: Some report(DeliveryNoterReport) was buggy and we needed to include an existing property (IsNeutralDelivery) from the businessObjects.DeliveryNote.Order - object. Actually we cant rollout the application (Dont ask :))

While debugging I noticed that from

IDeliveryNote dn = ((IDeliveryNote)this.DataSource);

i can access also the Order and the needed property (IsNeutralDelivery) maybe just fancy visual studio magic, so i tried to get the property with reflection like this:

bool neutralDeliveryAddressIsNeutralDelivery = (bool)dn.GetType().GetProperty("Order").GetValue(dn).GetType().GetProperty("IsNeutralDelivery").GetValue(dn.GetType().GetProperty("Order").GetValue(dn));

And yes, I retrieved the value and with that I could fix the bug (Only replace the printing.dll)

Question: Why I can get a instance of the DeliveryNote object when i got no references to the assembly that it belongs to.





Java - create generic class type at runtime

I have below line of code

 public static String getVOFromJson (String jsonString, Sting className) throws IOException {
     // className value is "MatchDetailsVO"
    MatchDetailsVO obj = mapper.readValue(jsonString, MatchDetailsVO.class);
}

Don't want to hard code MatchDetailsVO.class but want to create the class type at runtime using the variable className





Implementing equals, hashCode, and toString on java.lang.reflect.Proxy

I'm writing an application where I need to implement functional interfaces on runtime. I don't know in advance which interfaces to implement, but can resolve the Method object using reflection from the interface's Class object.

For the purpose of simplifying the question, let's say that I'm passing a Function object containing the implementation of the method.

Straight-forward stuff:

@SuppressWarnings("unchecked")
private <T> T implement(Class<T> interfaceType, Method m, Function<Object[], ?> f) {
    return (T) Proxy.newProxyInstance(
            getClass().getClassLoader(),
            new Class<?>[]{interfaceType},
            (proxy, method, args) -> {
                if (method.equals(m)) {
                    return f.apply(args);
                }

                // Calls to toString, hashCode, and equals go here.
                throw new UnsupportedOperationException(method.getName());
            }
    );
}

So calls to toString, hashCode, and equals currently fail. I clearly don't want that.

From the docs of java.lang.reflect.Proxy:

An invocation of the hashCode, equals, or toString methods declared in java.lang.Object on a proxy instance will be encoded and dispatched to the invocation handler's invoke method in the same manner as interface method invocations are encoded and dispatched, as described above. The declaring class of the Method object passed to invoke will be java.lang.Object. Other public methods of a proxy instance inherited from java.lang.Object are not overridden by a proxy class, so invocations of those methods behave like they do for instances of java.lang.Object.

So I can override these methods however I want. That's cool, but I would prefer not to.

Sure, I could make dummy implementations that do more or less the same thing (except for hashCode which is native) or capture some other dummy object (maybe the invocation handler itself) and invoke the method on that one. But I feel like I should be able to just "fall through" to the methods inherited from java.lang.Object the usual way. Or in other words, call the equivalent of super.hashCode() etc. directly on proxy.

Is there a good/standard way of doing that?





samedi 28 septembre 2019

Java change the class filed name using java reflection

If there is any way to change the field name of the new instance (foo) by using java reflection.

    Class Foo {
    String filed1;
    int filed2;
    }
Foo foo= new Foo();

By creating a new instance of Foo, access the foo filed1 and change it to hello





In Unity, how to find the type of a missing script?

a few of my objects now have 'missing' scripts on them, and I can't remember which script they once were.

I can't just delete them because I don't want to lose their the fields. I don't know why, but according to my experience, the invalid scripts may still remember its public field values. If I find the correct script type, the fields will come back.

I find an article about this but still don't understand:

How do I programmatically find name of missing script?

He uses Component.GetType(), but the missing scripts are null. I can't use GetType() of a null, is it? But someone says that article solves the problem. I am sure I missed something.

I really hope to find their types, or at least some hints, like public fields.





vendredi 27 septembre 2019

Instantiate object of a given class implementing an interfacte and add it to a List

I have an Interface "Instruction" and some instructions implement it (Add, Sub, Mul, Jmp...), to execute this instructions I store them on a List object and call an execute() method afterwards. I am reading this instructions from a file and I want to instantiate the proper class by means of the String read from the file but when I invoke the constructor.newInstance(...) I lose the type of the reference and I wont be able to invoke the methods without instanceofs and dirty casts (I want to avoid them).

List<Instruction> res = new ArrayList<>()
String className = "Add";
Class<?> classLoaded = Class.forName("instructions." + className);
Constructor<?> constructor = classLoaded.getConstructors()[0];
Object obj = constructor.newInstance(paramsOfConstructor);
res.add(obj);

This works as I want it to work but I want to avoid dirty casts as much as possible

Instruction obj = (Instruction) constructor.newInstance(paramsOfConstructor);
res.add(obj);

PD: paramsOfConstructor are all the objects/primitives I give to the constructor, I don´t include the code to obtain them because that would be a copy/paste of 30 or so lines. If needed I can copy them also.





Having import name as an argument, how to reference the import?

Having import name as an argument, how to reference the import?

Example:

import PolicyRegistry from './PolicyRegistry.json'

import web3 from './web3'

export const contractInstance = (name, address) =>
  new web3.eth.Contract(name.abi, address)

And I want to call like: module.contractInstance(PolicyRegistry, "address")





Finding if a Java class is final in JNI by using reflection

I'm trying to find if a java class is final from C++ (jni) by using reflection. So, having the next Java methods in Jni:

int modifiers = com.package_name.class_name.class.getModifiers();
Modifier.isFinal(mofidiers);

Everything works fine until calling the reflection for Modifiers.isFinal, which reports incorrectly that a none final class is actually final.

I've verified the Modifiers.getModifiers results, and as expected when not final it returns correctly 1, and when final returns 17. Yet Modifiers.IsFinal() also returns True for the "1" value result, which is public and not final.

This issue doesn't happen if Java, only in Jni. And I would prefer not to compare directly against the numeric results.

jboolean test(JNIEnv* env)
{
    jclass class_modifier = env->FindClass("java/lang/reflect/Modifier");
    jmethodID method_isFinal = env->GetStaticMethodID(class_modifier, "isFinal", "(I)Z");

    jclass class_Class = env->FindClass("java/lang/Class");
    jclass class_app = env->FindClass("com.package_name.Test");
    jmethodID method_getModifiers = env->GetMethodID(class_Class, "getModifiers", "()I");

    jint modifiers = env->CallIntMethod(class_app, method_getModifiers);
    return env->CallBooleanMethod(class_modifier, method_isFinal, modifiers);
} 




jeudi 26 septembre 2019

On loading an assembly/dll after a method is invoked via reflection, the method invocation throws "Object does not match target type" exception

I have a test tool developed using .net framework c#. I have a DLL which contains all the interfaces to and method that need to be invoked during runtime.

The application is started and this loads the assembly to memory using Assembly.Load(ReadAllBytes(path)) method and once the assembly is loaded, the types are fetched and required methods are invoked via reflection.

But after invoking a method if I load the assembly again and try invoking the same method, I get an exception from RunMethodInfo class CheckConsistency method.

"Object does not match target type"

Is it not possible to load the assembly after calls are made through reflection?

If I never run any method and load the assembly several times before, everything works fine. I am not understanding which object it is referring to ? Kindly help.





How can I get field value via reflection if name is different with field name

I have a class

 [BsonIgnoreExtraElements]
    public class CustomerModel
    {        
        public string BranchID { get; set; }       
        public string BranchName { get; set; }        
        public string ReceiverID { get; set; }
        public string ReceiverName{ get; set; }       

        }

I am writing a filter activity which can validate any field with specific value configured in MongoDB

"Exclude":[{"SourceCol":"Receiver Mode ID","Values":{"Value":["G","8","J"]}}

and written the comparing logic as

 public static object GetPropValue(object src, string propName)
        {
            return src.GetType().GetProperty(propName).GetValue(src, null);
        }

        public static bool CheckPropertyCompare(CustomerModel customer, Exclude item)
        {
            var propertyValue = GetPropValue(customer, item.SourceCol);
            return item.Values.Value.ToList().Contains(propertyValue);

        }

In this, the Receiver Mode ID from MongoDB is actually looking for ReceiverID and I am stuck as to how can I resolve this issue. The only option I can think of is Key-Value pair collection to fetch the field name. but would like to know if there is any options like Attributes which can ease this process.

TIA





How to get value from a KeyValuePair<> with unknown type

I have an object that is a KeyValuePair<> whose types I do not know. I need to get the Value of this KeyValuePair as object.

object kvpair = ... ;         // This is a KeyValuePair<K, V> with unknown K and V.
object value = kvpair.Value;  // I want to get the value of the kvpair

I understand this will involve using reflection.





Kotlin - Get Class

Given the following class:

data class Foo(val bar: Int)

How would I obtain a Class<T> for Foo...

val prop = Foo::bar

...from this property expression?





Bundle.classNamed(_ className: String) fails but NSClassFromString() work

I'm working on a proof of concept of loading plugin from a host application in Swift. I'm able to load a framework or a bundle on a Bundle class, NSClassFromString and Bundle.principalClass seems to work fine, but I'm not able to get any result from Bundle.classNamed function.

This is the piece of code I'm using:

for fullName in bundles {
    print("Loading framework: \(fullName)")

    if let bundle = Bundle(path: fullName), bundle.load(),
        let name = fullName.split(separator: ".").first {

        let typeNamed = bundle.classNamed(name + ".Plugin") as? NSObject.Type
        let typeNS = NSClassFromString(name + ".Plugin") as? NSObject.Type
        let typeNamedV2 = bundle.classNamed(name + ".PluginV2") as? NSObject.Type
        let typeNSV2 = NSClassFromString(name + ".PluginV2") as? NSObject.Type
        let typePrincipal = bundle.principalClass as? NSObject.Type

        print("From bundle.classNamed: \(initPlugin(from: typeNamed)?.description ?? "")" )
        print("From NSClassFromString: \(initPlugin(from: typeNS)?.description ?? "")" )

        print("From bundle.classNamed: \(initPlugin(from: typeNamedV2)?.description ?? "")" )
        print("From NSClassFromString: \(initPlugin(from: typeNSV2)?.description ?? "")" )

        print("From bundle.principalClass: \(initPlugin(from: typePrincipal)?.description ?? "")" )

        bundle.unload()
    }
}

The following is the output:

Loading framework: One.framework
From bundle.classNamed: 
From NSClassFromString: <One.Plugin: 0x102802060>
From bundle.classNamed: 
From NSClassFromString: <One.PluginV2: 0x102802060>
From bundle.principalClass: <One.Plugin: 0x102801650>
Loading framework: CommonInterface.framework
From bundle.classNamed: 
From NSClassFromString: 
From bundle.classNamed: 
From NSClassFromString: 
From bundle.principalClass: 
Loading framework: Bundle.bundle
From bundle.classNamed: 
From NSClassFromString: <Bundle.Plugin: 0x102b08040>
From bundle.classNamed: 
From NSClassFromString: <Bundle.PluginV2: 0x102b08f80>
From bundle.principalClass: <Bundle.Plugin: 0x102801ea0>

Project is configured for Swift 5 and Xcode 11 building.

Here you can find the complete source code of the POC:

https://github.com/lechuckcaptain/SwiftPluginArchitectureExample

Any hint/feedback are welcome!





Dynamically assign value to deeply nested list

I have a vector of strings, like

> cc <- c("a", "b", "c")
> cc
[1] "a" "b" "c"

...and I want to build a list (from scratch) with a structure like:

> ll <- list("a" = list("b" = list("c" = "hola")))
> ll
$a
$a$b
$a$b$c
[1] "hola"

What's the easiest way to dynamically access the elements of ll using cc?

I know, ultimately, that I want some syntax like:

ll[[cc[1]]][[cc[2]]][[cc[3]]] <- ... # or
ll[["a"]][["b"]][["c"]] <- ...

...which makes me think I want an apply or lapply, but it's not simply lapply(cc, ...), because that doesn't recursively apply the selection on ll. It would instead do something like:

ll[c[1]] <- ...
ll[c[2]] <- ...
ll[c[3]] <- ...

So I thought I'd need to use Reduce(). Because, essentially, what I'm trying to do is apply a function to a variable then apply a function to the result, then apply a function to the result, etc:

temp <-   ll[[c[1]]]
temp <- temp[[c[2]]]
temp <- temp[[c[3]]]
...

But I'm not sure this would work either, because we're not saving a reference to ll[[c[1]]] in temp, we're saving its value (the second line should throw an error).

I get the feeling that the solution will involve Reduce, calling the list access function as [[ and maybe a do.call(), but I'm lost. Any ideas?





mercredi 25 septembre 2019

C# Reflection on current async method

I'm trying to figure out of there is a somewhat straight forward way to get the reflected properties of the currently executing async method. I'm looking for the same properties that wuld be available if I were to just do something like this in a regular non-async method:

var method = (MethodInfo)MethodBase.GetCurrentMethod();

But if I'm in an async method, I am getting a MoveNext() method back from reflection, when using the above reflective code.

Would I just have to step up the call stack using StackTrace or StackFrame?

The only problem that I have with that is that it's somewhat manual. This code needs to by dynamic, as my implementation is going to be used in logging, and needs to be reliable and accurate across many applications. It needs to work with both async and synchronous methods / functions.

All that I can find out there currently is people using the baked in .net CallermemberName attribute, which gets the correct name of the currently executing method, but obviously I need more than that.

Any help would be greatly appreciated. Thanks!





Getting the fields with reflection

How it is possible:

myobject.getClass().getDeclaredFields();
for (Field f : fields) {
    LOGGER.debug(f);
}

DEBUG id
DEBUG name
DEBUG type

and when I try to get type field

myobject.getClass().getDeclaredFields("type");

then I get

NoSuchElementException: type





What is the best way to get class field value based on Key value config in Database

I have a class with fields

field1;
field2;
field3;

and in MongoDB, I have key-value payer which could be any of the fields with a specific value
eg: 1) "Field1" : "A"
or 2) "Field2" : "b" , "Field3" : "c"

How can I get the Class field-based value and compare with MongoDB asked Field name: Via reflection or any other better method Thanks





mardi 24 septembre 2019

Net Core: Find Data Type from Controller Action Method

How do I find the Return Type T from a Controller Action Method? I want to fill this with Reflection Later

GetBookResponse, I need to look at Return Type from Controller Action. This can error out sometimes, with error "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'"

Type returnType = action.ActionMethod.ReturnType.GenericTypeArguments[0].GetGenericArguments()[0];

from Code base:

[HttpGet("[Action]/{id}")]
[ProducesResponseType(typeof(GetBookResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(GetBookResponse), StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<GetBookResponse>> GetByBook(int id)
{
   var book = await bookservice.GetBookById(id);
   return Ok(book);
}

Referring question,

Net Core API: Make ProducesResponseType Global Parameter or Automate





Java reflection: check if Field an object

I have the below function, i want to check the field passed in parameters of type Object or (String, int, boolean...), is it possible to do this check?

private void delete(final Object source, Field field) throws IllegalAccessException {
    if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeDelete.class)) {
        final Object fieldValue = field.get(source);

        if (fieldValue instanceof List<?>) {
            for (Object item : (List<?>) fieldValue) {
                checkNDelete(item);
            }
        } else {
            checkNDelete(fieldValue);
        }
    }
}




Inconsistent behaviour with Java reflection 'invoke' method

Please see these example classes.

A.java:

// A is not public
class A
{
    public static void foo()
    {

    }
}

B.java:

package p;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class B
{
    public void invoke() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException
    {
        Class clazz = Class.forName("A");
        Method method = clazz.getDeclaredMethod("foo", new Class[0]);
        method.invoke(null, new Object[0]);
    }
}

C.java:

import java.lang.reflect.InvocationTargetException;

public class C extends p.B
{
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException
    {
        C c = new C();
        c.invoke();
    }

//  @Override
//  public void invoke() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException
//  {
//      Class clazz = Class.forName("A");
//      Method method = clazz.getDeclaredMethod("foo", new Class[0]);
//      method.invoke(null, new Object[0]);
//  }
}

The 'invoke' method in main in C fails with:

IllegalAccessException: Class p.B can not access a member of class A with modifiers "public static"

If the 'invoke' method in C is exactly the same as the overriden method in p.B. However, if it is uncommented no Exception is being thrown.

Why the difference?





C# Is there a way to resolve lamba expression`s delegate type in code

My goal is to support sorting in the application and expose it via REST API that would accept the parameter as a string.

Current implementation is along the lines of this:

GetUsers (Expression<Func<User, int>> sortExpression) {
 // Retrieve users ... 
 return users.orderBy(sortExpression);
}

Usage example:
var users = GetUsers(u => u.Id);

the Expression<Func<User, int>> sortExpression is widely used in our repository and changing it would be difficult.

What I'd like to do is to be able to swap the u => u.Id with something that is generated during run-time.

Something that I have so far is:

// sortBy is retrieved from the calling method.
var type = typeof(User).GetProperties().FirstOrDefault(x => x.Name == sortBy).GetType();

var sortExpression = Expression.Property(Expression.Parameter(typeof(User)), sortBy);

var parameter = Expression.Parameter(typeof(User));

var expressionBody = Expression.Lambda(typeof(Func<User, int>), sortExpression, parameter);

var users = GetUsers(expressionBody)

I can see at run-time that this does create an expression that fits my needs, but the error is Argument 5: cannot convert from 'LambdaExpression' to 'Expression<System.Func<User, int>>' even though the body of the expression is supposed to be set by typeof(Func<User, int>)





How to check if function execution is allowed in current context?

I use shared class in my project, so i want to check whether i can use Assemby.GetExecutingAssembly() without try/catch (big perfomance loss), because on one platform this method is not allowed, so i'm getting access exception
Access Exception: GetExecutingAssembly is not allowed in given context....





lundi 23 septembre 2019

Get nameof() passed parametr inside method

I am searching for solution for my project, where I have Dictionary(string, object) and helper method witch is trying to get some specific value from dictionary.

As you can see below, if I don't have stringKey, I am trying to get that stringKey from @object, (now it will return "object". Surely, I can do it in calling, but it looks too bad for me.

Is there any way to do that in this method?

public static bool GetValue<T>(Dictionary<string, object> dict, ref T @object, string stringKey = "")
        {
            if (string.IsNullOrEmpty(stringKey))
            {
               stringKey = nameof(@object);
            }
            dict.TryGetValue(stringKey, out var Object);
            if (Object != null)
            {
                @object = (T)Object;
                return true;
            }
            return false;
        }

Example of calling:

DPH.GetValue(dictParam, ref Browser);

Expectations in method is that stringKey will be "Browser", as it will be in this case:

DPH.GetValue(dictParam, ref Browser, nameof(Browser));

There are specific needs and we are not able to refactor that Dictionary to our object or our class at this moment, calling with nameof() is possible, but not a solution.

Thank you for you time!





How to get ES6 class constructor from class name?

Given the following code:

class MyClass {}

Is there a way to get the MyClass constructor from the string, MyClass? I'm looking for something analogous to .NET's Assembly.GetType.

Use case:

A user of a product authors their own classes via some sort of extensibility; and these classes should be able to be loaded from the global scope by the product when the product is given the name of a given class.

I understand that in most cases this would likely be a terrible design pattern lacking encapsulation, but nonetheless I am curious if this type of reflection is possible in any ECMAScript version. The way I work around this is to have each class "register" itself using a helper function (or class decorator!) from the main product.

P.S.

I notice that while function declarations alter the global scope, class definitions do not:

function hithere() {}
globalThis["hithere"] // hithere(){}

class hithere {}
globalThis["hithere"] // undefined





C# Create default value for class, e.g. through reflection

Let's say I have a class A:

public class A 
{
    private int value;
    public A() => value = 0;
    public A(int value) => this.value = value;
}

And I have some method, with a parameter list where some are defaulted:

public void SomeMethod(int i, float f, string s = "", A a = null)

Now is there some way, e.g. through reflection, to be more smart about this parameter list? I would like to be able to do something like the following, so I don't need to check for null everywhere:

public void SomeMethod(int i, float f, string s = "", A a = Default) // should use the empty constructor!

Is this possible with C#?





ReflectionException error appear at Drupal 8 project . When I am going to clear cache , error coming

When I going to clear cache from admin panel , error appear i.e

The website encountered an unexpected error. Please try again later.ReflectionException: Class Drupal\mymodule\Controller\MyClass does not exist in ReflectionMethod->__construct() (line 136 of core/lib/Drupal/Core/Entity/EntityResolverManager.php). Drupal\Core\Entity\EntityResolverManager->setParametersFromReflection(Array, Object) (Line: 221)

But at my local system there is no error.

I did some R & D with it. I found some difference between my local phpinfo and server phpinfo. Found different between. Different found at Reflection property.

For my local there display some version of Reflection , but at server no version found.

Local : enter image description here

Server :

enter image description here

Please provide me any solution.





dimanche 22 septembre 2019

C# Create Class by Concatenating String

public class Customer
{
    public int ProductId { get; set;},
    public string ProductName { get; set;},
    public string ProductDescription { get; set;},
    public float SalesAmount { get; set;}
}

public class Tracker<T>
{
    [Required, ValidateObject]
    public T Body { get; set; }
    public Date date { get; set; }
    public string GUID{ get; set; }
}

Is there a way to create a class, automatically by periods or concatenating string, which will auto compile in Visual Studio

public class CustomerTracker : Tracker<Customer>
{
}

So instead of creating 100s of class as above, I can take any class and it will generate this class automatically. Does any C# Library function permit this?

so Customer.Tracker = public class CustomerTracker : Tracker<Customer>
Customer.ListTracker = public class CustomerTracker : Tracker<IEnumerable<Customer>>

or Food.Tracker = public class FoodTracker : Tracker<Food>





How to get annotations of a caller method from another class

I am using jdk1.8.0_221 and I want to load specific configuration inside the constructor of super class based on calling two different types of methods. I am seeking for the best practice and preferably a convenient approach.

package test;
public class A extends Z{
    @Marker1
    public void f1() {
        Z.g();
    }
    @Marker2
    public void f2() {
        Z.g();
    }
}

package test;
public class B extends Z{
    @Marker1
    public void f3() {
        Z.g();
    }
    @Marker2
    public void f4() {
        Z.g();
    }
}

package core;
public class Z{
    public Z() {
        //I want to determine here that which type of method (Marker1 or Marker2) calls constructor
    }
    public static void g(){
        //some code goes here
    }
}

Note1: There are many methods from different classes that calls Z.g(), so I could not use the explicit name of class to get methods and its annotations.

Note2: All of configurations should be done inside the constructor of super class of Z.

Note3: The g() method is not necessarily static.

I have tried the following snippet but getMethodName() return always <init>:

public Z() Throws NoSuchMethodException, ClassNotFoundException{
    StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
    StackTraceElement ste = stElements[3];// or stElements[2]
    Class<?> aClass = Class.forName(ste.getClassName());
    String methodName = ste.getMethodName();
    Method method = aClass.getMethod(methodName);
    Annotation[] annotations = aClass.getAnnotations();
    for (Annotation annotation : annotations) {
        if (annotation.getClass().equals(Marker1.class)) {
             //load conf1
             break;
         } else if (annotation.getClass().equals(Marker2.class)) {
             //load conf2
             break;
         }
     }
}

Also, I have tried many solutions in stackoverflow and other communities which not worked properly.





How to create a proxy of an unbound generic type with ByteBuddy?

As an exercise, I need to extract the method name from a method reference. For example:

interface Marker {}

interface Foo extends Marker {

    String foo();
}

class MethodNameExtractor {

    static <T extends Marker> String extract(Function<T, String> methodReference) throws Exception {
        var proxy = (T) new ByteBuddy()
            .subclass(Marker.class)
            .method(not(isDeclaredBy(Object.class)).and(returns(String.class)))
            .intercept(InvocationHandlerAdapter.of(MethodNameExtractor::invoke))
            .make()
            .load(MethodNameExtractor.class.getClassLoader()).getLoaded().getConstructor()
            .newInstance();
        return methodReference.apply(proxy);
    }

    static Object invoke(Object proxy, Method method, Object[] args) {
        return method.getName();
    }
}


class MethodNameExtractorTest {

    @Test
    public void itExtractsTheMethodName() {
        assertEquals("foo", extract(Foo::foo));
    }
}

But the test throws:

java.lang.ClassCastException: class Marker$ByteBuddy$EHoz8bj6 cannot be cast to class Foo (Marker$ByteBuddy$EHoz8bj6 is in unnamed module of loader net.bytebuddy.dynamic.loading.ByteArrayClassLoader @4009e306; Foo is in unnamed module of loader 'app')
    at MethodNameExtractor.extract(MethodNameExtractor.java:3)
    at MethodNameExtractorTest.itExtractsTheMethodName(MethodNameExtractorTest.java:5)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:532)
    ...

So I cannot cast the proxy to T? How can I produce a proxy that can be passed as the argument of the method reference?





How to check if a class has overriden a default method from an interface using Reflection in Kotlin or Java?

I have an interface with a default method, and two classes which implement this interface. One of the classes overrides the default method, and the other does not.

interface MyType {
  fun giveHello(): String = "Hello!"
}

class Polite: MyType {
  // Does not override giveHello()
}

class Rude: MyType {
  override fun giveHello(): String = "I don't like you"
}

I get access to the giveHello method using reflection like this:

val methodOfPolite = Polite::class.java.getDeclaredMethod("giveHello")
val methodOfRude = Rude::class.java.getDeclaredMethod("giveHello")

There's one weird thing here. The polite class does not override the giveHello method, but the declaringClass of this method object still points to Polite.

So is there a way I can check whether the class actually did override the default interface method or not?

My use case looks something like this (assuming we can get the behaviour I'm asking for in a property called isOverriden):

if (methodOfPolite.isOverriden) {
  // do something
} else {
  // do something else
}





Converting an anonymous type to a dictionary

I am attempting to create a function that converts an anonymous type to a dictionary. I was going over the accepted answer in this link thread. However I am getting the error

"Cannot use lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type"

This is what I am trying to do

public Dictionary<string,string> convert(dynamic dtype)
{
 var props = content.GetType().GetProperties();
 var pairs = props.Select(x => x.Name + "=" + x.GetValue(a, null)).ToArray();  // <----Exception
 var result = string.Join("&", pairs);
 return result
} 

Any suggestion on how I can fix this ? I am trying to do this

       var student= new
        {
            // TODO: Make this figure out and return underlying device status.
            type = "Active",
        };



 var dict = convert(student);





samedi 21 septembre 2019

Can i know if an object is a custom object?

I am writing an annotation processor and i need to scan all classes with certain annotation to get all fields and create json object with same structure of the class.

For example:

public class Person {
    private String name;
    private String surname;

    /*getter and setter*/
}

My output is:

{
    "name": "string",
    "surname": "string"
} 

Now i am wondering how can i handle classes like this one:

public class PhoneNumber {
    private String countryCode;
    private String phoneNumber;

    /*getter and setter*/
}

public class Person {
    private String name;
    private String surname;
    private PhoneNumber phoneNumber;

    /*getter and setter*/
}

i would like get output like this:

{
    "name": "string",
    "surname": "string",
    "phoneNumber": {
        "countryCode": "string",
        "phoneNumber": "string"
    }
}






C# Resolve Concrete type from Generic Interface

I have the following scenario:

  1. I have several derived exceptions classes that implements a base exception
    //Base exception type
    public class SaberpsicologiaException : Exception
    {
    }

    //One of the derived exception class
    public class MovedPermanentlyException : SaberpsicologiaException
    {
        public string CannonicalUri { get; private set; }

        public MovedPermanentlyException(string cannonicalUri) 
            : base($"Moved permanently to {cannonicalUri}")
        {
            this.CannonicalUri = cannonicalUri;
        }
    } 


  1. For each exception class I want to implement an exceptionHandler that will return an ActionResult, which will implement a common interface:
    interface ISaberpsicologiaExceptionHandler<T>
        where T : SaberpsicologiaException
    {
        ActionResult Result(T exception);
    }

    public class MovedPermanentlyExceptionHandler 
        : ISaberpsicologiaExceptionHandler<MovedPermanentlyException>
    {
        public ActionResult Result(MovedPermanentlyException exception)
        {
            var redirectResult = new RedirectResult(exception.CannonicalUri);
            redirectResult.Permanent = true;

            return redirectResult;
        }
    }


  1. When I catch an exception derived from SaberpsicologiaException I want the appropiate handler to run:
    public class ExceptionHandlerFilter : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            base.OnException(context);

            HandleResponseCodeByExceptionType(context);
        }

        private void HandleResponseCodeByExceptionType(ExceptionContext context)
        {
            var exception = context.Exception;

            if (!CanHandle(exception))
            {
                return;
            }

            var mapping = new Dictionary<Type, Type>
            {
                { typeof(MovedPermanentlyException),  typeof(MovedPermanentlyExceptionHandler) }
            };

            var handlerType = mapping[exception.GetType()];
            var handler = Activator.CreateInstance(handlerType);

            handler.Result(exception); //<- compilation error 
            //handler is type "object" and not MovedPermanentlyExceptionHandler
        }
    }

I tried to resolve it with the Activator (Reflection), but I get to the problem of not really having and object of type ISaberpsicologiaExceptionHandler< [runtime exceptiontype] > so I can't have use the type properly.

In summary the problem is that I have an exception type and I want to get the ISaberpsicologiaExceptionHandler for that exception type, I guess I could use more reflection to just execute the 'Result' method, but I would like to do it a little bit more ellegant.





vendredi 20 septembre 2019

Java Reflection call to method with Generic parameters

How to call a method through a Reflection, when it has a generic parameter, like bellow snippet -

@Test
    public void testOptional() throws NoSuchMethodException, InvocationTargetException,
            IllegalAccessException
    {
        AtomicReference<ClassA> atomicReference = new AtomicReference<>(new ClassA());
        ClassB classB = new ClassB();

        Method method = MyTest.class.getDeclaredMethod("doSomething", AtomicReference.class, ClassB.class);
        method.setAccessible(true);
        method.invoke(atomicReference, classB);
    }

    private void doSomething(AtomicReference<ClassA> classA, ClassB classB){

        System.out.println("Hi do not poke me, I am working!");
    }

It gives me -

java.lang.IllegalArgumentException: object is not an instance of declaring class





How to set values of parent objects using reflection in C#

I have code that would recursively parse an unknown object structure. But I want to be able to change values of the member objects of the parent object. How can I do this with this code?

    void CompareObjects(ref object currentObject)
    {
            Type currentType = currentObject.GetType();
            PropertyInfo[] properties = currentType.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                object current_object = currentType.GetProperty(property.Name).GetValue(currentObject));
                CompareObjects(ref current_object);
            }
    }





How to access a field within a static inner class with a generic type? (very difficult)

I'm stuck on this problem for almost 3 months now and just can't resolve it myself. I hope it's possible. I'm trying to inject this code with my own custom entity class, which is hard to access, because the class is static and the field is final. Somehow i'm not sure if the generic type is a problem on accessing it.

    public class EntityTypes<T extends Entity> {

        [some code here]

        public interface b<T extends Entity> {
            T create(EntityTypes<T> entitytypes, World world);
        }

        public static class a<T extends Entity> {
            private final EntityTypes.b<T> a;
            [more code here]
        }
    }

So far i tried to use Reflections, but i keep getting:

java.lang.IllegalArgumentException: Can not set net.server.EntityTypes$b field net.server.EntityTypes$a.a to net.server.EntityTypes

       ReflectionUtils.setFinal(EntityTypes.a.class, EntityTypes.VILLAGER, "a", (EntityTypes.b<CustomVillager>) CustomVillager::new);





C# get all string combinations between 2 arrays

I have 2 string arrays:

string[] baseAssemblyNames

For instance ['Core', 'Web', 'Data']

string[] projectAssemblyNames

For instance ['Project1', 'Project2']

Result:

['Project1.Core', 'Project1.Web', 'Project1.Data', 'Project2.Core', 'Project2.Web', 'Project2.Data']

I want all combinations between these 2, now I am using 2 foreach to iterate and combine them.

        foreach(var projectAsm in projectAssemblyNames)
        {
            foreach(var baseAsm in baseAssemblyNames)
            {
                try
                {
                    var asm = Assembly.Load($"{projectAsm}.{baseAsm}");
                    asmList.Add(asm);
                }
                catch { }
            }
        }

Is there a better solution for this in terms of performance when we have a lot of projects where we want to load the assembly for scanning.





Why does reflection over `IReadOnlyList<>` does not return the property `Count`?

Under .NET Core 2.2, when entering the following C# expression in the Immediate Window of Visual Studio 2019:

typeof(IReadOnlyList<>).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy)

I am getting the following return:

{System.Reflection.PropertyInfo[1]}
     [0]: {T Item [Int32]}

This is rather odd, because I would expect the IReadOnlyCollection<>.Count property to returned due to the BindingFlags.FlattenHierarchy flag.

Also calling typeof(IReadOnlyList<>).GetInterfaces() returns:

{System.Type[3]}
    [0]: {Name = "IReadOnlyCollection`1" FullName = null}
    [1]: {Name = "IEnumerable`1" FullName = null}
    [2]: {Name = "IEnumerable" FullName = "System.Collections.IEnumerable"}

And typeof(IReadOnlyList<>).GetInterfaces()[0].GetProperties() returns:

{System.Reflection.PropertyInfo[1]}
    [0]: {Int32 Count}

I am a bit at a loss here. Could someone explains why isn't the Count property returned as per my first statement above?





Have a common base type for all my custom annotations

So, I have created several custom annotations:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Foo {

}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Bar {

}

Those annotations are used in my functions:

public class Worker {

   @Foo
   public void doTaskOne() {...}

   @Bar
   public void doTaskX() {...}

   ...
}

I want to use java reflection to check if certain annotation is declared in one method.

for (Method m : methods) {
      if (m.isAnnotationPresent(Foo.class)) {
        ...
      } else if (m.isAnnotationPresent(Bar.class)) {
        ...
      }
}

The problem is that since in Java, custom annotation @interface is not able to be extended. I mean this is illegal:

public @interface Bar extends MyBaseAnnotation{
}

That's I am not able to have a base @interface for all my custom annotation class Foo and Bar. So, if I have a new custom annotation created, I need to add more else if condition in above method checking code, which sucks! Is there anyway to get rid of this problem? What I want to achieve is to generalize my method checking code to :

for (Method m : methods) {
     if (m.isAnnotationPresent(MyBaseAnnotation.class)) {
         ...
     }
}

How to achieve it?





How to getMethod from a variable number of parameters in java reflection

I need to test a java class with a huge number of functions. I'm using cucumber so I could call a function that gets only a parameter or I could call another with 7 or 8 parameters (all of them are string, fortunatelly).

So I make a table like that:

| objectname | funcname  | [varX]             | 
| objectname | funcname2 | [varY]             |
| objectname | funcname3 | [varZ, varX, varY] |
| objectname | funcname  | [varZ]             |

In the code I could convert the third column in a variable list of parameters, that is easy, but my problem is to call the getMethod function. I don't want to define a list of:

objectName.getClass().getMethod("functionName", varList.get(0).getClass());
objectName.getClass().getMethod("functionName", varList.get(0).getClass(), varList.get(1).getClass());
objectName.getClass().getMethod("functionName", varList.get(0).getClass(), varList.get(1).getClass(), varList.get(2).getClass());
....

Is there a way to solve it with something like

objectName.getClass().getMethod("functionName", list2ArgList);

? Sorry for not to be more precise.





Class.getDeclaredMethods throwing NoClassDefFoundError for class method with no arguments and void return type

I want to get the names of all the public methods (void return type and no arguments) of a class1 which is dependent on some other class2. I am loading class through UrlClassLoader. Now when i am calling getDeclaredMethods, it is throwing NoClassDefFoundError caused by ClassNotFoundException.

I am having 3 mvn modules as

  1. SampleClassLoader: Using it to get the methods of class of Module1.
  2. Module1: Its class using the reference to classes of Module2. And has a dependency of Module2 in its pom.xml also.
  3. Module2

The whole module structure looks like: Project Structure

ClassLoadingTest
|----- Module1
|       |--- pom.xml
|       |--- src/main/java/
|       |               |--- com.classloadingtest.module1
|       |                           |
|       |                           |--- Module1Class1.java
|       |                           |--- Module1Class2.java
|       
|----- Module2
|       |--- pom.xml
|       |--- src/main/java/
|       |               |--- com.classloadingtest.module2
|       |                           |
|       |                           |--- Module2Class.java
|       
|----- SampleClassLoader
|       |--- pom.xml
|       |--- src/main/java/
|       |               |--- com.classloadingtest.sampleClassLoader
|       |                           |
|       |                           |--- SampleClassLoader.java

Module1Class1.java

public class Module1Class1 {
    public void claas1Fun() {
        Module2Class module2ClassObj = new Module2Class();
        module2ClassObj.module2Fun();
    }
}

Module1Class2.java

public class Module1Class2 {

    public void class2Fun(){
        try {
            Module2Class module2ClassObj = new Module2Class();
            module2ClassObj.module2Fun();
        } catch(Exception e ){

        }
    }
}

Module2Class.java

public class Module2Class {

    public void module2Fun(){

    }
}

SampleClassLoader.java

public class SampleClassLoader {
    public static void main(String[] args) {

        try {

            URL mainSourceClassPathURL = new URL("file:" + System.getProperty("user.dir") + "/ClassLoadingTest/Module1/target/classes/");

            URL[] urls = { mainSourceClassPathURL};
            ClassLoader classLoader = URLClassLoader.newInstance(urls);

            Class<?> testCaseClass = classLoader.loadClass("com.classloadingtest.module1.Module1Class1");
            Method method[] = testCaseClass.getDeclaredMethods();

            for (int i = 0 ; i < method.length ; i++) {
                System.out.println(method[i].getName());
            }

        } catch (Exception e){
            e.printStackTrace();
        }

    }
}

Now, When Running the SampleClassLoader for class Module1Class1 prints

claas1Fun

But when running for class Module1Class2 it is giving NoClassDefFoundError as:

Exception in thread "main" java.lang.NoClassDefFoundError: com/classloadingtest/module2/Module2Class
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.getDeclaredMethods(Class.java:1975)
    at com.classloadingtest.sampleClassLoader.SampleClassLoader.main(SampleClassLoader.java:26)
Caused by: java.lang.ClassNotFoundException: com.classloadingtest.module2.Module2Class
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:814)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 4 more

I am having two questions here that is:

  1. When using try catch, why it is giving error?
  2. If the class1 is already loaded at classLoader.loadClass then why getDeclaredMethods method need to load dependent classes?




jeudi 19 septembre 2019

Why can't c# infer casting?

So i recently started working with reflection for the first time, and found GetType() to know the original type of an object, even if it is just stored as an object.

foreach(object o in (IEnumerable) property.GetValue(element))
{
    List(o, verbose, int.MaxValue, subIncludes[attribute.Name], indents + 4);
}

So here o is actually getting passed into a generic method. I found that after getting passed in, o.GetType(); returns the actual class type and not System.Object which surprised me. For arguments sake lets say the type is Product. So if the type is already known, why is it necessary to cast o to Product like so Product p = (Product) o;instead of just doing Product p = o? Why not infer that casting is the desired outcome since the type is already known?





How to dynamically transform a Java Interface to make its return type wrapped in Futures?

Given the following interface:

interface DummyAPI {
  int f1(int x);
  String f2();
}

What I want is a way to write a class like this:

class Futurized<T> {
}

where effectively, the methods of Futurized<DummyAPI> would effectively be:

    Future<Integer> f1(int x);
    Future<String> f2();





Trying to change the value of a property at runtime using reflection results in NullPointerException

I have a class that I'm writing unit tests for:

import java.io.File;

public class MyLogger {

    private final File logFile = new File("default");

    public File getLogFile() {
        return this.logFile;
    }
}

I would like to change the value assigned to logFile from within another class, e.g:

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Main {

    public static void main(String[] args) throws NoSuchFieldException, SecurityException, Exception {

        MyLogger logger = new MyLogger();
        System.out.println(logger.getLogFile());

        setFinal(MyLogger.class.getDeclaredField("logFile"), new File("changed"));
        System.out.println(logger.getLogFile());
    }

    private static void setFinal(Field field, Object newValue) throws Exception {
        field.setAccessible(true);

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

        field.set(null, newValue);
    }
}

But I'm getting the output/exception below:

default
Exception in thread "main" java.lang.NullPointerException
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:57)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:75)
    at java.lang.reflect.Field.set(Field.java:764)
    at Main.setFinal(Main.java:23)
    at Main.main(Main.java:12)





Get interface properties of object through property declaration

I want to get the interface properties if they exist from the container object of the property. I can get the container class, I think, but the interface of doing "as ISportParameters" returns null, but the interface is certainly on the object.

public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

            if (attributes.OfType<DisplayAttribute>().ToList().Count > 0)
            {
                 // Want ISportParameters properties
                var model = modelAccessor.Target.GetType().GetField("container").GetValue(modelAccessor.Target);

            }

            return modelMetadata;
        }

}





Get Class fields from annotated Object in annotation processor

i'm working on my first annotation processor. I'm trying to get fields of class through annotation on declared object(that is a field of a method). For example:

public class Person {
    private String name;
    private String surname;
}

...
public void myMethod(@MyAnnotation Person person) { 
    /*...*/
}
...

Through @MyAnnotation i want to get 'name' and 'surname' fields.

Is that possible? I did something of similar with method's field:

...
for (Element element : roundEnvironment.getElementsAnnotatedWith(AnnotationOnMethod.class)) {
    ExecutableElement method = (ExecutableElement) element;
    List<? extends VariableElement> parameters = method.getParameters();
    parameters.forEach(p -> {
        /*code here for parameter*/
    });
}
...


Thanks in advance, Luca.





java reflect Method - How to get all content code of method? [duplicate]

This question already has an answer here:

I want get all content code of method (System.out.println("foo1"); and System.out.println("foo2"); in may case) but I do not find?

import java.lang.reflect.Method;

public class DisplayMethod {

    public static void main(String[] args) {
        final Method[] methods = DisplayMethod.class.getDeclaredMethods();
        for (final Method method : methods) {
            System.out.println(method.getName() + " " + method.toGenericString());
        }
    }

    private void foo1() {
        System.out.println("foo1");
    }

    private void foo2() {
        System.out.println("foo2");
    }

}

actual result:

main public static void sof.DisplayMethod.main(java.lang.String[])
foo1 private void sof.DisplayMethod.foo1()
foo2 private void sof.DisplayMethod.foo2()

target result:

foo1  private void sof.DisplayMethod.foo1() { System.out.println("foo1"); }
foo2  private void sof.DisplayMethod.foo2() { System.out.println("foo2"); }





How to check the type of typed class ?>

I am passing the parameter in the method which has declared to be accepted parameter type class...other, after passing the parameter like String.class and Integer.class I want to know the type (class of) parameter which has been passed in this methods.

What parameter I received, I converted it into object and tring to checking the type but it is not working.

public void processVarargIntegers(String label, Class<?>... others) {

    System.out.println(String.format("processing %s arguments for %s", others.length, label));
    Arrays.asList(others).forEach(a -> {

        try {
            Object o = a;
            if (o instanceof Integer) {
                System.out.println(" >>>>>>>>>>>>> Integer");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}

public void processVarargIntegers(String label, Class<?>... others) {

    System.out.println(String.format("processing %s arguments for %s", others.length, label));
    Arrays.asList(others).forEach(a -> {

        try {
            Object o = a;
            if (o instanceof Integer) {
                System.out.println(" Integer");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}

if a is the instance of the integer System.out.println(" Integer"); should be executed





mardi 17 septembre 2019

No definition found for qualifier: How to solve Kotlin reflection is not available when creating modules with Koin test?

I'm trying to create a simple white-box test with Koin. After setting qualifier to pass a mock as parameter to an instance (or supposedly what I want to do) I'm receiving an error which says:

org.koin.core.error.NoBeanDefFoundException: No definition found for qualifier='null' & class='class com.stonetree.imagebucket.main.repository.GalleryRepositoryImpl (Kotlin reflection is not available)'

This is my test class:

class GalleryRepositoryTest: AutoCloseKoinTest() {

    private val module = module {
        named("repository").apply {
            single<GalleryRepository>(this) { GalleryRepositoryImpl() }
            single { GalleryViewModel(get(this.javaClass)) }
        }
    }

    private val repository: GalleryRepositoryImpl by inject()
    private val vm: GalleryViewModel by inject()

    @Before
    fun setup() {
        startKoin { loadKoinModules(module) }
        declareMock<GalleryRepositoryImpl>()
    }

    @Test
    fun uploadImage_withEmptyUri_shouldDoNothing() {
        vm.delete("")
        verify(repository).delete("")
    }
}

I also tried a similar approach with Robolectric runner, but after creating the module in Application file, my mock wouldn't be invoked using verify(repository).delete("").

How can I manage to solve this problem and move forward with this simple test?





R8 stripping out Kotlin companion object needed for reflection

I have a class with a companion object which implements a factory interface.

class GoalInspectorData(
    ...
) {

    companion object : DataClassFactory<GoalInspectorData> {

        override fun fromV8Object(v8Object: V8Object): GoalInspectorData {
            ...
        }
    }
}

I have some code which examines this class at runtime using reflection to see if the class provides a factory method. It does this by checking to see if the class has a companion object (companionObjectInstance) and, if so, if that companion object implements the factory interface.

internal inline fun <reified T> convert(obj: Any): T {

    val companionObject = T::class.companionObjectInstance

    @Suppress("UNCHECKED_CAST")
    return when {
        T::class in builtInClasses -> obj as T
        companionObject as? DataClassFactory<T> != null -> companionObject.fromV8Object(obj as V8Object)
        else -> throw IllegalArgumentException("No converter for type ${T::class}")
    }
}

This all works fine in a debug build.

It fails in a release build with R8 enabled (minifyEnabled true in build.gradle). It fails because companionObjectInstance returns null.

I'm using the "don't optimize" Proguard config:

proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

and in my own proguard-rules.pro I've added just about every -keep rule I can imagine in an attempt to retain this companion object, but nothing works. R8 is determined to strip it out.

For example:

-keep class my.package.** {
    *;
}
-keep interface my.package.** {
    *;
}

-if class **$Companion extends **
-keep class <2>
-if class **$Companion implements **
-keep class <2>

Are there any other -keep rules or configuration options which would instruct R8 to retain this companion object?





PHP: Accessing a class constant with a dynamic string value as name?

This is my enum:

abstract class Environment extends BasicEnum {
    const LOCAL = "LOCAL";
    const DEVELOPMENT = "DEVELOPMENT";
    const STAGING = "STAGING";
    const SANDBOX = "SANDBOX";
    const PRODUCTION = "PRODUCTION";
}

In some other class (a Twig extension) I do:

public function getCurrentEnv()
{
    $env = getenv("ENVIRONMENT");
    if($env !== false) {
        if(Environment::isValidName($env)) {
            $env = strtoupper($env);
            return Environment::$env;
        } else {
            throw new \Exception("The ENVIRONMENT variable should be defined correctly.");
        }
    }
}

The error is:

Access to undeclared static property: AppBundle\Twig\Extension\Enum\Environment::$env

I tried things like:

AppBundle\Twig\Extension\Enum\Environment::{$env}

But it seems like this is not working for constants. The value of $env is LOCAL and I know it is a defined constant, because I check it before.

What is the correct syntax to access a class constant with a dynamic string value being the name?





lundi 16 septembre 2019

How can I run compile and run Scala code programmatically

I have the following code and I would like to compile it on the fly and run it.

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("Hello, world!")
  }
}

So far I have tried something like below:

import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

object MainScala {
  def main(args: Array[String]): Unit = {
    val toolbox = currentMirror.mkToolBox()
    val source =
      """
        |object HelloWorld {
        |  def main(args: Array[String]): Unit = {
        |    println("Hello, world!")
        |  }
        |}
        |""".stripMargin
    val tree = toolbox.parse(source)
    val binary = toolbox.compile(tree)
    var c = binary.getClass
    val m = c.getMethod("main", classOf[Array[String]])
    val params = Array("Apple", "Banana", "Orange")
    m.invoke(null, null)
  }
}

After toolbox.compile(tree) I am not able to get the Class object of the compiled code.





List of Reflected Classes and Iterating through the properties

Basically I want to make a reflected version of a class in List<> form so I can iterate through the list, then do the same thing on its properties so I can iterate through its properties as well.

I have gotten to where I can iterate through a single instance of a class, but I cant seem to figure out a solution for a List<> of reflected classes.

basically I want List[i].property[j] = GetData(c);

Below is the code I was messing with to get the List of reflected classes and their properties.

Type reportType = typeof(ReportController);
Type reportListType = typeof(List<ReportController>);

PropertyInfo[] properties = reportListType.GetProperties();


I also tried =typeof(List<>); but passing in the reportType, for whatever reason the formatting won't show it on SO.

Below is the references I have accessed.
C# instantiate generic List from reflected Type
https://docs.microsoft.com/en-us/dotnet/api/system.type.makegenerictype?view=netframework-4.8
Set object property using reflection

any and all help is appreciated.





java.lang.InstantiationError when creating instance of static inner class with Objenesis

I am trying to create a utility method that should be able to deep-clone any object. (Object.clone() only works on Object implementing Cloneable and I heard it's flawed anyways.)

I am using Objenesis to create new instances of objects without the use of constructors.

However, when trying to clone a JFrame I get the following Exception:
(using this class because I think it should be a good and complex test)

java.lang.InstantiationError: [Ljava.util.concurrent.ConcurrentHashMap$Node;
    at sun.reflect.GeneratedSerializationConstructorAccessor12.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:48)
    at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)

I am open to any solution, not necessarily limited to Objenesis.

My Code:

private static ObjenesisStd OBJENESIS = new ObjenesisStd();

@SuppressWarnings("unchecked")
public static <T> T clone(T object, boolean deep){
    if(object == null){
        return null;
    }else{
        try {
            T clone = (T) OBJENESIS.newInstance(object.getClass());
            List<Field> fields = ReflectionUtil.getAllFieldsInHierarchy(object.getClass());
            for(Field field : fields){
                boolean isAccessible = field.isAccessible();
                boolean isFinal = ReflectionUtil.isFinal(field);
                field.setAccessible(true);
                ReflectionUtil.setFinal(field, false);
                Class<?> type = field.getType();
                if(!deep || type.isPrimitive() || type == String.class){
                    field.set(clone, field.get(object));
                }else{
                    field.set(clone, clone(field.get(object), true));
                }
                field.setAccessible(isAccessible);
                ReflectionUtil.setFinal(field, isFinal);
            }
            return clone;
        } catch (Throwable e) {
            e.printStackTrace();
            //throw new RuntimeException("Failed to clone object of type " + object.getClass(), e);
            return null;
        }
    }
}


public static void main(String[] args) {
    GetterSetterAccess access = new GetterSetterAccess(JFrame.class);
    JFrame frame = new JFrame("Test Frame");
    for(String attr : access.getAttributes()){
        System.out.println(attr + " " + access.getValue(frame, attr));
    }

    System.out.println("----------------------------------------------");
    frame = clone(frame, true);


    for(String attr : access.getAttributes()){
        System.out.println(attr + " " + access.getValue(frame, attr));
    }
}





Get TypeBuilder from defined type in an AssemblyBuilder

Based on the other question, a Type cannot be converted into a TypeBuilder.

However, we have a method that returns a AssemblyBuilder. It already has types built and defined. We can know that some types might not be correctly converted, however, there is no direct method to get to the TypeBuilder and manually fix the issues.

It seems to me very strange to be returning an AssemblyBuilder and not provide a method to revise the constructed objects before finalizing it into an Assembly, so maybe I'm missing something.

So, Is there a way where we can take a defined type from a AssemblyBuilder and either revise it or replace it outright?





Mapstruct, automatic detection of source and target mappings

I have a problem regarding the mapping of Mapstruct. Since I need to handle a huge amount of classes, I want to severly use automatic code generation and mapping.

My current issue is to map a xml class (viewmodel) to a Bo. The viewmodel ist automatically generated code from a xsd. Each class variable has a tag "XmlElement" which carries the name of a database table column. This string is also named in the Bo in the "Column" annotations. I want to make Mapstruct somehow connect each source with a target automatically according to the annotations. Performance is not an issue.

Can anybody give me a hint on how this is possible?

Thanks to all Oliver

BO:

@Entity
@Table(name = "table_y")
public class ClassY implements Identifiable<AVId> {

    @Valid
    @EmbeddedId
    private AVId id;

    @Column(name = "rg_m_id")
    @Digits(integer = DataTypeSize.NUMBER_22, fraction = 0)
    private Long mandantId;

    @Column(name = "vp_m_id")
    @Digits(integer = DataTypeSize.NUMBER_22, fraction = 0)
    private Long vertragspartnerMandantId;

    @Column(name = "ee_kurzbez")
    @Size(max = DataTypeSize.VARCHAR_16)
    private String eeKurzbezeichnung;

    @Column(name = "vp_kurzbez")
    @Size(max = DataTypeSize.VARCHAR_16)
    private String vertragspartnerKurzbezeichnung;

    @Column(name = "v_beschreibung")
    @Size(max = DataTypeSize.VARCHAR_4000)
    private String vBeschreibung;

    //getter and setter
}

XML (ViewModel):

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "T_AV_Row", propOrder = {})
public class TXRow {

    @XmlElement(name = "rg_m_id", required = true)
    protected Long rgMId;

    @XmlElement(name = "vp_m_id", required = true)
    protected Long vpMId;

    @XmlElement(name = "ee_kurzbez", required = true)
    protected String eeKurzbez;

    @XmlElement(name = "vp_kurzbez", required = true)
    protected String vpKurzbez;

    @XmlElement(name = "v_beschreibung", required = true)
    protected String vBeschreibung;

    //getter and setter
}

Mapstruct interface:

@Mapper()
public interface IXYMapper {

    IXYMapper INSTANCE = Mappers.getMapper( IXYMapper.class );

    ClassY xToy(TXRow tXRow);
}





Can i create a json example with empty values from only an objects type?

we are doing some stuff with webhooks and events. I wanna create an example of a json payload based on the type of the event send to the webhook.

Lets say i have a class like this:

public class TestClass{
    public int Id {get;set;}
}

Now what i would like, is to be able to create something like

{
    "id": 0
}

just from knowing typeof(TestClass).

I do not want to create instances of my objects, because some of them are rather complex and has all sorts of parameter requirements.

I just want an json representation without any of the values filed in.

Any ideas?





Load classes from current thread and jar

My goal is in a thread when we reach a method to load some more classes from a jar.How can I set to the current thread a new class loader with the currently loaded class + load some classes from a .jar?





C# : propertyinfo always empty

i have an issue with c# reflection. The object I want to reflect is the following :

public partial class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
    }

    public decimal CustomerId { get; set; }

    public string AlexaAccessToken { get; set; }

    public string GoogleHomeAccessToken { get; set; }
}

The code I use to reflect is the following :

    Dictionary<string,string> GetReplacement(ApplicationUser applicationUser)
    { 

        Dictionary<string, string> toRet = new Dictionary<string, string>();

        PropertyInfo[] propertyInfos;
        propertyInfos = typeof(ApplicationUser).GetProperties(BindingFlags.Public);

        Array.Sort(propertyInfos,
            delegate (PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
                { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });


        foreach (PropertyInfo propertyInfo in propertyInfos)
        {
            toRet.Add(propertyInfo.Name,propertyInfo.GetValue(applicationUser).ToString());
        }

        return toRet;
    }

The problem is that the dictionary is always empty because propertyinfo is always empty. What is the problem? Thank you all in advance.





go-cmp when comparing 2 structs treats empty interface value as int and flat64

So I am using go-cmp github.com/google/go-cmp/cmp. To compare 2 structs. Both the structs are of same type. When comparing the result I am seeing the following difference.

I am using go v1.12

type Sample map[string]interface
var a Sample
var b Sample

cmp.Diff(a,b)


// Somewhere in code I do this
a["sample"] = 1 // this is optional.

So if I compare a and b I see the diff where it interprets the same field as int(0) and float64(0)

-: int(0)
+: float64(0)

I expect the diff to be nil





Dynamically casting in C# recursively with Reflection

I've searched this issue on the internet, I found some ways but they didn't suitable for my problem. This is my code and I need to cast fields in my class that is the type of some another class.

    public void CheckObjectFormatValues(object o)
    {
        FieldInfo[] fields = o.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach (System.Reflection.FieldInfo prp in fields)
        {

            if (prp.FieldType.BaseType != typeof(ValueType))
            {
                if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.ArrivalType")
                    CheckObjectFormatValues((ArrivalType)prp.GetValue(o));

                if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.Cell")
                    CheckObjectFormatValues((Cell)prp.GetValue(o));

                if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.ObjectType")
                    CheckObjectFormatValues((ObjectType)prp.GetValue(o));

                if (prp.FieldType.FullName == "IServiceProvider.Datacontracts.ObjAction")
                    CheckObjectFormatValues((ObjAction)prp.GetValue(o));
            }
            else
            {
                var value = prp.GetValue(o).ToString();
                if (value == "-1")
                    throw new Exception("Error");
            }
        }
    }

Is there any way to refactor my If block with recursive function and cast dynamically?





dimanche 15 septembre 2019

Powershell. Get types from .net assembly returns Cannot resolve dependency to assembly 'System.Runtime, Version=4.2.1.0'

I have a .net project and I need to fetch list of method out of it using powershell, so I do

$testSuite = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom("c:\dev\project\integrations-tests-poc\Container1.IntegrationTests\bin\Debug\netcoreapp2.2\Container1.IntegrationTests.dll")

Then when I'm trying to

$testSuite.GetTypes()

It returns

Cannot resolve dependency to assembly 'System.Runtime, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.

I checked my nuget package storage, there aren't any package with this version and I cannot download it from anywherer. What am I doing wrong?





Unable to find/edit field with reflection, when dotPeek & stackoverflow questions decompiler clearly show it

I've been working on threads for a project of mine, and I've started using thread names for logging purposes. The main thread of my application is being renamed to an empty string (not by me), so I need to change it manually. The problem is, the Name property of a Thread is write-once, and since it's already been set, I am unable to change it normally. I looked around a bit and was able to find This question that seemed promising. When ever I run it though, I get null reference exceptions. I examined further, and the GetField() method is returning null. I checked with Jetbrains dotPeek and I can clearly see the m_Name field, along with it's property:

private Context m_Context;
private ExecutionContext m_ExecutionContext;
private string m_Name; //<- This
private Delegate m_Delegate;
private CultureInfo m_CurrentCulture;

My code to get the field is

thread.GetType().GetField("m_Name", BindingFlags.Instance | BindingFlags.NonPublic);

As soon as I run it, it returns null. I tried using typeof(Thread), to no avail.

Finally, I decided to brute force it, and decided to try and try with every single binding flags combination:

Stopwatch stopwatch = Stopwatch.StartNew();
HashSet<FieldInfo> fieldInfos = new HashSet<FieldInfo>();
//Loop over every single bit combination
for (int i = 0; i < 0x01111111; i++)
{
    BindingFlags f = (BindingFlags) i;
    FieldInfo[] infos = thread.GetType().GetFields(f);
    foreach (FieldInfo info in infos) fieldInfos.Add(info);
}
Debug.Log($"Time to search: {stopwatch.Elapsed.TotalMilliseconds:n0}ms");
stopwatch.Restart();
Debug.Log(fieldInfos.Count);
foreach (FieldInfo info in fieldInfos)
{
    Debug.Log(info.Name);
    Thread.Sleep(10);
}
Debug.Log($"Time to log: {stopwatch.Elapsed.TotalMilliseconds:n0}ms");

Output

How do I get it to find the field properly?





Why is `MemberExpression.Member` ownership not resolved the same way reflection does?

Consider the following code:

using System;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        var propFromReflection = typeof(Bar).GetProperty("Property");

        Expression<Func<Bar, int>> expression = bar => bar.Property;
        var memberExpr = expression.Body as MemberExpression;

        var propFromExpression = memberExpr.Member;

        Console.WriteLine("Reflection says " + propFromReflection.DeclaringType.Name);
        Console.WriteLine("Expression says " + propFromExpression.DeclaringType.Name);
    }
}

public abstract class Foo
{
    public abstract int Property { get; set; }
}

public class Bar : Foo
{
    public override int Property { get; set; }
}

The output in console will state that

Reflection says Bar

Expression says Foo

Why are they different? How come the Expression engine won't get the exact MemberInfo instance used within the lambda expression? Technically it has everything it needs to do so, doesn't it?





The TypeConverter method of CanConvertFrom result in false for a byte types

I'm trying to validate if a object Value is a valid value for a property name with:

public class FooGenericClass<TEntity>
{
    public string PropertyName { get; set; }
    public object Value { get; set; }
    public bool IsValid
    {
        get
        {
            if (this.PropertyName == null || this.Value == null)
            {
                return false;
            }

            PropertyInfo propertyInfo = typeof(TEntity).GetProperty(this.PropertyName);

            if (propertyInfo != null)
            {
                Type propType = propertyInfo.PropertyType;
                TypeConverter converter = TypeDescriptor.GetConverter(propType);
                if (converter.CanConvertFrom(this.Value.GetType()))
                {
                    return true;
                }
            }

        return false;
    }
}

The IsValid works fine for int types but for byte type the CanConvertFrom returns false.

Example:

var foo1 = new FooGenericClass<BooClass>()
{
    PropertyName = "MyByte",
    Value = 1
};
var foo2 = new FooGenericClass<BooClass>()
{
    PropertyName = "MyInt",
    Value = 1
};

class BooClass
{
    byte MyByte { get; set; }
    int MyInt { get; set; }
}

The problem that foo1.IsValid getter return false, wheres foo2.IsValid return true. any suggestions?





How to call methods on generic type parameters Kotlin

Is there a way to call methods in a generic class of type F on the same generic type?

In my example F is the generic type parameter, but I don't have any variable declared of this type.

Or is there a way at compile-time to declare a variable which is of the same type parameter F at run time?

    class AggDBTreeImpl<K,V: Serializable,A: 
    Serializable,D,F:Function<V,A,D>> (
        private val url: String,
        private val table: String,
        private val kp: KeyParser<K>
    ): AggDBTree<K,V,A,D,F> where K:Comparable<K>, K: Serializable {

         F.method()
    }





samedi 14 septembre 2019

Reflection using generic types when class is unknown

I'm loading a model with reflection:

        private void LoadAssemblies()
        {
            Assembly assembly = Assembly.LoadFrom(modelDll);
            var types = assembly.GetTypes();
            inputType = assembly.GetType(types.Where(x => x.FullName.Contains("Input")).FirstOrDefault().FullName);
            outputType = assembly.GetType(types.Where(x => x.FullName.Contains("Output")).FirstOrDefault().FullName);
            inputModel = Activator.CreateInstance(inputType);
            outputModel = Activator.CreateInstance(outputType);
            inputModel = JsonConvert.DeserializeObject(jsonPredict);
        }

Then I need to call a method with two generyc types

var predEngine = mlContext.Model.CreatePredictionEngine<typeof(inputModel), typeof(outputModel)>(mlModel); //here I cant convert this model loaded at runtime into a type to this generic method.

I've tried

var instance = Activator.CreateInstance(typeof(ModelOperationsCatalog)); //eror here
//System.MissingMethodException: 'No parameterless constructor defined for this object.'

instance.GetType()
                .GetMethod("CreatePredictionEngine")
                .MakeGenericMethod(inputType, outputType)
                .Invoke(this, new object[] { });*/





Delegate.CreateDelegate - method arguments are incompatible

Given aMethodInfo for the following method

public class MyEffects
{
  public Task Test(object action, IDispatcher dispatcher)
  {
    return Task.CompletedTask;
  }
}

Why does the following CreateDelegate code throw System.ArgumentException: method arguments are incompatible?

Delegate.CreateDelegate(
    type: typeof(Func<object, IDispatcher, Task>),
    method: discoveredEffect.MethodInfo);

As does this

Delegate.CreateDelegate(
    type: typeof(Func<object, object, IDispatcher, Task>),
    method: discoveredEffect.MethodInfo);





How to change the entity field before saving by using AspectJ?

I have some entities that implement the Auditable interface:

public interface Auditable {
    Audit getAudit();
    void setAudit(Audit audit);
}

Audit encapsulates some common information such as date of creation, date of updating, etc. For example, the document entity:

@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "document")
public class Document implements Auditable {

    @Embedded
    private Audit audit;

    // SKIPPED

}

I want to use AspectJ to set Audit before saving the Document entity. I do it by this way:

@Aspect
@Component
public class AuditSetterAspect {

    private final String DEFAULT_USER_NAME = "admin";

    @Autowired
    private UserService userService;

    @Pointcut("execution(* whitepappers.dao.repositories.*.save(*))")
    public void savePointcut() { }

    @SneakyThrows
    @Around("savePointcut()")
    public Object addCommonData(final ProceedingJoinPoint proceedingJoinPoint) {
        final int affectedEntityIndex = 0;
        String userName = DEFAULT_USER_NAME;
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (nonNull(auth)) {
            Object obj = auth.getPrincipal();
            if (obj instanceof UserDetails) {
                userName = ((UserDetails)obj).getUsername();
            }
        }

        User currentUser = userService.findByLogin(userName);

        Object[] affectedEntities = proceedingJoinPoint.getArgs();
        if (Auditable.class.isAssignableFrom(
                affectedEntities[affectedEntityIndex].getClass())) {
            Auditable entity = (Auditable) affectedEntities[affectedEntityIndex];
            Audit audit = ofNullable(entity.getAudit()).orElse(new Audit());

            if (isUpdateAction(audit)) {
                audit.setDateUpdate(now());
                audit.setUserUpdate(currentUser);
            } else {
                audit.setUserCreate(currentUser);
                audit.setDateCreate(now());
            }
            entity.setAudit(audit);
        }

        return proceedingJoinPoint.proceed(affectedEntities);
    }

    private boolean isUpdateAction(Audit audit) {
        return !isNull(audit.getUserCreate());
    }
}

When I create a Document entity, the audit is set correctly. But when I update an entity, the audit doesn't change. Here I always get a new audit object:

Audit audit = ofNullable(entity.getAudit()).orElse(new Audit());

How can I get an existing audit object from a previously created entity for further updating?

I would be very grateful for the information.

Thanks to all.





How to get access to any property or field using expression

I want to get value from property or field by name using expression. It is possible?

class MyClass
{
    public string Value {get;set;} = "testvalue";
}
// like this
var delegate = Expression.Lambda<Func<MyClass, string, string>>(/* some parameters*/ ).Compile();
var myClass = new MyClass();
var result = delegate.Invoke(myClass, "Value");
// result == "testvalue"





vendredi 13 septembre 2019

How can I get classes from a package using reflection?

I have a package like "org.bar.baz". I need to get classes from this package using reflection.

Package p = Package.getPackage("org.baz.bar");
Class[] classes = ?;

How can this be implemented (if at all possible) ? Thank! :)





Do I need nullable and not nullable PropertyType checks? C#

I changed something in my app so it wont run now, however I'm wondering if this code:

 if (props.PropertyType == typeof(DateTime) || props.PropertyType == typeof(DateTime?))

should be written as this

if (props.PropertyType == typeof(DateTime?))

I would expect that checking for DateTime? covers DateTime as well or ?





AutoMapper to copy EF connected object without line and lines of code

This is a bit of a long one, so get yourself a coffee (other quality libations are available).

In an effort to write as little code as possible, keep my apps simple, testable, maintainable and clean, and to turn apps around in quickly.

I'm using a really simple method I wrote to copy from MVC objects to EF objects to save me writing loads of code when I have objects with loads of properties. In fact, I don't care what the object is or how many properties it has. I just want to copy it without prepping loads of code in a map or somewhere.

Please don't start off on view models and all that, and quoting me the big book of Microsoft. All I'm looking for a little advice from my peers and the community in general about AutoMapper The example here is simple so you can see what I'm getting at.

What I didn't want to do and I've seen it lots, was:-

item ... //the original item populated from somewhere, MVC database, who cares, its got stuff in it

Item newItem = new Item();

newItem.prop1 = item.prop1;
newItem.prop2 = item.prop2;
newItem.prop3 = item.prop3;
newItem.prop4 = item.prop4;
//... you get the idea

or even this ...

Item newItem = new Item {  
    prop1 = item.prop1,
    prop2 = item.prop2,
    prop3 = item.prop3,
    prop4 = item.prop4,
    //... you get the idea
}

So I came up with this. A function called CopyObject that does excatly what I want it to do, so I don't have to care about any objects or how many properties it has, I write one line of code anywhere I need to that does all the work for me. See the example below

//show the item in a view, typically a bootstrap popup dialog
public IActionResult EditItem(int ID)
{
    Item item = _dbContext.Items.Where(i => i.ID == ID).FirstOrDefault();

    if (item == null)
        item = new Item { ... property defaults ... };

    return View(item);
}

//save the item from the view
[HttpPost]
public JsonResult EditItem(Item item)
{
    Item newItem = _dbContext.Item.Where(i => item.ID).FirstOrDefault();
    if (newItem == null)
    {
        newItem = newItem {... property defaults ... };
        _dbContext.Items.Add(newItem);
    }

    //here is the fun part
    CopyObject(item, newItem, ...ignore some properties);

    _dbContext.SaveChanges();

    return new JsonResult( new { result = "success", message = "Updated" });
}

CopyObject is my function, it does nothing clever except it uses reflection to copy properties from one object to another (EF)object without losing the connection to EF. CopyObject looks like this (below). I won't bore you with the implementation, but simply, it uses reflection to copy properties between any two objects.

At the moment it only copies from the top-level because that's all I need it to do right now, but it wouldn't be a massive stretch to get it to copy a hierarchy of stuff.

It doesn't actually care that the object types match, it doesn't care that the property types match. It only cares that if finds properties on each object with the same name, and it will then attempt to copy the values. You can also specify properties not to copy.

    /// <summary>
    /// Copies the values of the properties from one object to another object with the same properties if they exist.
    /// This will try to copy from any two objects whether they are the same object type or not
    /// </summary>
    /// <param name="CopyFrom">The object to copy property data from</param>
    /// <param name="CopyTo">The object to copy property data to</param>
    /// <param name="DontCopy">A (string) list field names not to be copied</param>
    /// <returns>True if at least one property was copied, otherwise false</returns>
    public bool CopyObjects(object CopyFrom, object CopyTo, params string[] DontCopy) {...}

There is nothing wrong with my code it works perfectly fine just the way I need it to. I don't have any extra work to do when I start a new project no matter how many properties any of the objects have. I just import that

Anyway, because I'm not published or any kind of authority my code is getting frowned upon. I've been told AutoMapper can do the same thing but I can't seem to make it. I always get a disconnected object that I then have to do some tomfoolery to get it back into the EF and ultimately database.

So my question is. How do you acheive the same thing using Automapper without lots of code?. Remember my goal is not to have to write loads of code, in prep or in line.





jeudi 12 septembre 2019

How to Get a Double object's Value using Reflection in C#?

I have a nested class that I am navigating to parse a double object

In debugger I can see the object's value is a number

However I cannot simply cast and add it to a list this way,

values.Add((double)current_object);

Because of a System.InvalidCastException: 'Specified cast is not valid.' exception

How can I retrieve the double object's Value using reflection?

This is what I tried so far:

current_object.GetType().GetProperty("Value").GetValue(current_object) but current_object.GetType().GetProperty("Value") returns null

Thank you