vendredi 2 juillet 2021

C# Pass DataMembers to expression body using reflection

I have some models that I save into XML which look like this:

public class Point
{
    [DataMember(Name = nameof(Name))]
    public string Name { get; set; }

    [DataMember(Name = nameof(X))]
    public double X { get; set; }

    [DataMember(Name = nameof(Y))]
    public double Y { get; set; }

    and so on...
}

These models have a SaveToXml and a LoadFromXml method:

public virtual XElement SaveToXml(XElement obj)
{
    this.SaveToObject(s => s.Name, obj);
    this.SaveToObject(s => s.X, obj);
    this.SaveToObject(s => s.Y, obj);

    return obj;
}

public virtual void LoadFromXml(XElement obj)
{
    this.LoadFromObject(s => s.Name, obj);
    this.LoadFromObject(s => s.X, obj);
    this.LoadFromObject(s => s.Y, obj);
} 

The SaveToObject and LoadFromObject methods are extension methods of XElement which get/set the value of the passed DataMember (Name, X, Y, etc.) from the XElement obj passed.

My problem is that these models tend to get pretty big and every added/removed member needs a change in the SaveToXml and LoadFromXml methods. So I have been trying to find a way to get all DataMembers of my model using reflection and try passing those for the Save/Load methods, but I am doing something wrong.

This is what I came up with so far:

var props = typeof(Point).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(DataMemberAttribute)));

foreach (var prop in props)
{
    this.TrySave(prop.GetValue(this), element);
}

This does not cause an error for the save (it asks for a reference type in the Load method), but it does not save the values nor throws an exception.





PrivilegedActionException in quarkus when using JOOQ

First up; the code works. I'm getting an exception in my log but no actual error actually occurs. The correct output gets sent to the client, the app keeps running, as far as I can tell everything is fine. Yet I have an error.

I'm using Quarkus and JOOQ. There is an endpoint that triggers a select().fetchInto(Custom.class). The endpoint still returns the correct data. But the log shows this error:

2021-07-02 12:58:25,938 SEVERE [com.sun.xml.bin.v2.run.ref.opt.Injector] (executor-thread-1) null: java.security.PrivilegedActionException: java.lang.NoSuchMethodException: sun.misc.Unsafe.defineClass(java.lang.String,[B,int,int,java.lang.ClassLoader,java.security.ProtectionDomain)
        at java.base/java.security.AccessController.doPrivileged(AccessController.java:558)
        at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.<clinit>(Injector.java:166)
        at com.sun.xml.bind.v2.runtime.reflect.opt.AccessorInjector.prepare(AccessorInjector.java:51)

The exception is long. And goes through a bunch of different pieces of code:

at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
...
at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:99)
...
at javax.xml.bind.ContextFinder.find(ContextFinder.java:393)
...
at org.jooq.tools.Convert.<clinit>(Convert.java:223)
...
at org.jooq.impl.SelectImpl.fetchInto(SelectImpl.java:3936)
...
at my-code-here-somewhere

Right now I'm running as a simple uber-jar. Native compilation worked fine a while ago but I haven't tested if this error persists in the native binary.

I'd like the error to not be there. I'm fine with a solution to suppress it but if possible I'd like to know who is failing to do something here and if there is a real problem.

Some versions and stuff:

  • Installed Java: 16
  • Targeted Java: 11
  • Quarkus: 1.13.7.Final
  • io.quarkiverse.jooq:quarkus-jooq : 0.2.0




jeudi 1 juillet 2021

Class

public <T> T genericMethod(Class<T> tClass)throws InstantiationException ,
  IllegalAccessException{
        T instance = tClass.newInstance();
        return instance;
}

Object obj = genericMethod(Class.forName("com.test.YourClass"));

This is a typical code for java to use generic method return an instance of specific class. Instance of Class is pass as an variable and new instance is created by calling the constructor through reflection.

I am still confused by the mechanism of reflection and Class class. My question is, if the class information of YourClass will be erase from the Class instance, when calling the reflection method, why it can create an YourClass but not an object? Shouldn't an Object be created?





Apply filter on all annotated fields of a POJO (Java)

Imagine that there are such kind of POJO classes, that just keep data:

public class Pojo() {

  @AnnotatedProp
  String someField;

  SubPojo someSubPojo;

  String someOtherFieldA;

  String someOtherFieldB;
}

public class SubPojo() {

  @AnnotatedProp
  String someSubField;

  Integer someOtherFieldC;
}

someField of Pojo and someSubField of SubPojo are marked special with the @AnnotatedProp property.

I'd like to modify an object of type Pojo. All String fields with @AnnotatedProp annotation should be modified. A "filter" should modify the values of these fields, e.g. replace some characters inside.

I tried with FieldUtils / simple reflection, but I ended up in stack overflows (the exception AND this forum).

What would be the best way to filter these fields?

Thanks for help.





New Instances using Reflexion into Dictionary (c#)

I try use System.Reflection to create new Instances of some clases. First of all ,will be find the classes using some filters like "Where and EndWith", when all the classe are load, then create a list. For each type into the list make the instance of the class using

"viewModelType.Assembly.CreateInstance(viewModelType.FullName)".

 GetType().Assembly.GetTypes()
                 .Where(type => type.IsClass)
                 .Where(type => type.Name.EndsWith("ViewModel"))
                 .ToList()
                 .ForEach(viewModelType => 
      ViewContainer.AddComponent(viewModelType.Assembly.CreateInstance(viewModelType.FullName)));
               

so at the last line the plan is to set the instances into a Dictinary using the Static Method ViewContainer.AddComponent(T).

here the code snipe for these Class and his Method:

private Dictionary<Type, object> Component { get; } = new Dictionary<Type, object>();

        /// <summary>
        /// Add Component 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="componentName"></param>
        public void AddComponent<T>(T componentName)
        {
            Component[typeof(T)] = componentName;
        }

So the Reflexion logic works well i meant the classes that i search are found, exactly the are 3, my problem it's that wen i want to add the instances using "AddComponent" will be just add one of then , may be cuz Createinstance(..) returns object? and the dictionary dont accept more than once?, in this case can some say me how i can add correctly these 3 elements into the dictionary?.

I know that the Method "AddComponent" works well , for example when we use the folling call

ViewContainer.AddComponent(New SomeClassName)

Thanks for advance

(Project use .net Framework 4.5)

Best Regards Javanto





Using JAVA Reflection how to create custom JSON object mapping

I have a json Object in the below format, I need to assign the values from Json to java object, But the label name in JSON and class is different.

{
  FirstName: "Sample",
  LastName: "LName",
  Address: [
    {
      type: "Temp",
      street: "test stree",
      
    },
    {
      type: "Perm",
      street: "test stree",
      
    }
  ]
}

Class Parent{

private String Name1;
private String Nama2;
private List<Address> address;}

Class Address{

Private String type;

private String data;
}

I wanted to implement the custom object mapper using Java reflection. the mapping is as below, But I am not getting idea to implement this, Any valuable suggestion or usage of external api would help me to achieve the scenario.

Json Object name Jave Class object Name FirstName ---------- Name1 LastName ---------- Name2
Address.type ------- Address class type Address.street ----- Address class data





Play: Get information if Action is deprecated inside of itself

I have a situation like this:

@Singleton
class FooController @Inject() () {
   @deprecated("Use bar instead", "22.10.2020")
   def getFoo(param: Int): Action[AnyContent] =
      userAction { ... }
}

Somewhere else:

def userAction(f: (Request[AnyContent], UserInfo) => Future[Result]): Action[AnyContent] =
   simpleAction { ... }

def simpleAction(f: Request[AnyContent] => Future[Result]): Action[AnyContent] =
   ...

The simpleAction takes care of things like logging, de- and serialization and some other metadata related stuff. It isn't only used by userAction, but I added this as an example that shows the layering of methods isn't flat.

What I need to find out in simpleAction, for purposes of logging, is if one of the callers (in this case getFoo) has been marked as @deprecated.

I think it's possible by parsing the stack trace, and then reflecting on the method to find all annotations. But this solution isn't perfect.