lundi 31 janvier 2022

golang how to access promoted type

I have a 'common' structure promoted within two specific structures. For example:

type common struct {
    name string
}

type apple struct {
    common
}

type orange struct {
    common
}

Details specific to apple and orange are omitted.

I have a type-specific map of each, e.g., map[string]*apple and map[string]*orange.

I am trying to make a single function that can extract the common pointers. From what I've tried so far, reflection appears required.

My function is:

func getFruitArray(theMap interface{}) []*common {
    m := reflect.ValueOf(theMap)
    cf := make([]*common, 0, m.Len())
    for _, mk := range m.MapKeys() {
        v := m.MapIndex(mk)
        cf = append(cf, v.Interface().(*common))
    }

    return cf
}

This function fails at cf = append(cf, v.Interface().(*common)) with:

panic: interface conversion: interface {} is *main.apple, not *main.common

Is there a way to access the promoted struct common without specifically referencing apple or orange in this function?

playground example





Setting member variables by name in Spock

I am writing a Spock integration test for a function that takes a DTO, that has a lot of member variables. The functionality to test is that one user role is allowed to change some member variables, but if that user tries to change one of the other fields, it should fail.

I don't want to manually write a test for every single field, so I figured, I could be using a where: table like so:

where:
fieldname | value | isAccepted
"fieldA"  | "val" | true
"fieldB"  | "val" | false
...

For that, I'd have to be able to set the fields by the name in a string. In Java I'd have to use reflection for that. In Python I could just use setattr(object, fieldname, value) for that.

Since I writing the test in Groovy, is there something idiomatic for that?





Check if Annotation is inherited

I have an annotation and three classes like this:

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}

@MyAnnotation
public class MySuperClass {}

public class MySubClassA extends MySuperClass {}

@MyAnnotation
public class MySubClassB extends MySuperClass {}

Is there any way I can determine if a present annotation is inherited or declared directly at the class?

Something like a method public boolean isInherited(Class<?> clazz, MyAnnotation annotation) that should only be called if the annotation is present.

Exptected output:

isInherited(MySuperClass.class, MySuperClass.class.getAnnotation(MyAnnotation.class)) --> false
isInherited(MySubClassA.class, MySubClassA.class.getAnnotation(MyAnnotation.class)) --> true
isInherited(MySubClassB.class, MySubClassB.class.getAnnotation(MyAnnotation.class)) --> false




samedi 29 janvier 2022

Invalid class name from reflection .NET 6

I'm trying to get all classes from the namespace:

var commands = Assembly.GetExecutingAssembly().GetTypes()
            .Where(t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal))
            .ToList();

I have only one class in this namespace:

enter image description here

But, in commands variable I have 2 classes:
enter image description here

I don't understand why it breaks. I also solved this trouble by adding
!t.FullName!.Contains("<>") in where statement of commands, but I don't think that it's perfect solution.
Can somebody explain me why reflection breaks?





How to call generic Method from generic Interface c#?

Error Message:System.ArgumentException: 'Object of type '<>f__AnonymousType2`1[System.String]' cannot be converted to type 'ConsoleApp2.IRequestSimple'

There are my types Request/Response

    public interface IRequestSimple
    {
        public string Field { get; set; }
    }

    public interface IResponseSimple
    {
        public string Answer { get; set; }
    }

    public class MyConsumer : IConsumer<IRequestSimple>
    {
        public async Task Consume(ConsumeContext<IRequestSimple> context)
        {
            Console.WriteLine(context.Message.Field);
            await context.RespondAsync<IResponseSimple>(new { Answer = "Good job" });
        }
    }

I'm trying to call GetResponse but using reflection

var client = mediator.CreateRequestClient<IRequestSimple>();
var response = client.GetResponse<IResponseSimple>(new { });

There is my issue, I need to specify type to calling GetResponse

var requestType = typeof(IRequestSimple);
var responseType = typeof(IResponseSimple);
            
Type type = mediator.GetType();
var methodInfo = typeof(IClientFactory).GetMethods().Where(s => s.Name == "CreateRequestClient" && s.IsGenericMethod).First();
var genericMethod = methodInfo.MakeGenericMethod(requestType);
dynamic requestClient = genericMethod.Invoke(mediator, new object[] { Missing.Value });

Type type1 = requestClient.GetType();
var methodInfo1 = type1 .GetMethods().Where(s => s.Name == "GetResponse").First();
var genericMethod1 = methodInfo1.MakeGenericMethod(responseType);
//Here is my requestClient should be with specified type
var task = (Task)genericMethod1.Invoke(requestClient, new object[] { new { Field = "1" }, Missing.Value, Missing.Value });
await task.ConfigureAwait(false);





vendredi 28 janvier 2022

How to find installed Excel language in C#

Currently I am using the below code to get the excel language

        string strExcelLang = string.Empty;            
        Microsoft.Office.Interop.Excel.Application tExcel = new Microsoft.Office.Interop.Excel.Application(); 
        CultureInfo cExcelCulture = new CultureInfo(tExcel.LanguageSettings.get_LanguageID(Microsoft.Office.Core.MsoAppLanguageID.msoLanguageIDInstall));
            strExcelLang = cExcelCulture.ToString();
        if (strExcelLang.ToUpper().Equals("EN-US") || strExcelLang.ToUpper().Equals("JA-JP"))
        {
            // do something;
        }

However sometimes in client machine we are getting the following error,

System.Runtime.InteropServices.COMException
  HResult=0x80080005
  Message=Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).
  Source=mscorlib
  StackTrace:
   at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType)
   at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType)
   at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)

Using the excel interop is causing this error. But it won't occur in all machines. Since it is occurring in certain machines, I would like to change the approach to get the installed excel language.

What are the other ways we can achieve this?





jeudi 27 janvier 2022

Initialize Class with Generic Types in Another AppDomain

I am trying to setup a tool I can use to load non-version-specific assemblies from a config/database/etc. at runtime, execute code as needed, and then unload them to eliminate overhead. (My situation has many possible alternate code flows, and I'd like to not force a recompile of the entire app to onboard or edit a single flow)

I've setup a library to run AppDomain.CreateInstanceFromAndUnwrap to initialize classes in separate AppDomains, but as far as I can tell, this doesn't support generic type arguments on the class.

How can I initialize classes with type arguments in a different AppDomain than the executing code from a type name and assembly path? If that's not possible, is there any way to load assemblies in a different AppDomain than the executing code such that it handles dependencies automatically the same way that AppDomain.CreateInstanceFromAndUnwrap does (assuming I could then find a way to call Type.MakeGenericType that executes in the temporary AppDomain from the original AppDomain)?





Reflection shows DeclaredFields but returns no fields for simple C# class

I have a very simple class defined like:

public class Apple
{
   public string MyString1;
   public string MyString2;
   public string MyString3;
}

When I try to retrieve the fields or properties of this type, or an instance of it, Reflection returns nothing. However, in Visual Studio, I can see the fields available in "DeclaredFields" member of the type.

Any idea what is going on here? The only thing I can think is maybe the namespaces are causing an issue. Both the location where I am trying to retrieve the property info and the location where the type is defined are in the same top-level namespace, but the former is using the namespace of the latter.

Here is the reflection code:

public static class ReflectionHelper {

public
static
List<string>
GetPropertyNames(Type T)
{
    try
    {
        var properties = T.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        if (properties != null)
        {
            return properties.ToList().Select(property => property.Name).ToList();
        }
        var fields = T.GetFields(BindingFlags.Public | BindingFlags.Instance);
        if (fields != null)
        {
            return fields.ToList().Select(field => field.Name).ToList();
        }
    }
    catch (Exception) { }
    return null;
}
}

I am calling it like:

var apple = new Apple();
var stuff = ReflectionHelper.GetPropertyNames(typeof(Apple));




Invoking class under com.android.server.display in android using java reflection - possible or not?

I tried the following code but it throws "java.lang.ClassNotFoundException: com.android.server.display.DisplayModeDirector". Is this not possible or I'm just not doing it right?

val displayModeDirector = Class.forName("com.android.server.display.DisplayModeDirector")
val con = displayModeDirector.getConstructor(Context::class.java,Handler::class.java)
con.newInstance(applicationContext, Handler(Looper.getMainLooper()))

I am referring to this class





mercredi 26 janvier 2022

Using Scala Toolbox is it possible to define a case class and use it later into eval code?

I would like to give the case class definition to the Toolbox and be able to use them later when I do the eval. The Toolbox should be able to know the definitions of the case classes.

For example, I am able to define a case class named Authentication with args email

      import scala.reflect.runtime._
      import scala.reflect.runtime.universe._
      import scala.tools.reflect.ToolBox
      val cm = universe.runtimeMirror(getClass.getClassLoader)
      val toolBox = cm.mkToolBox()
      val myClass: ClassDef = q"case class Authentication(email: String)".asInstanceOf[ClassDef]
      val definedClass  = toolBox.define(myClass)
      println(definedClass)

Then I would like to recall it into my Eval expression and match it

  val myCode =
    q""" def myFunction(x:Any){
       x match{
        case Authentication(param) => println("Auth received!")
        }
       }"""

  toolBox.eval(myCode)

But it tells me, Authentication was not found. Any idea of how to accomplish it?





How to set Dictionary

If the model has a Dictionary<string, string> property, I want to set values with reflection.

My model is as below,

 public class DataModel
 {
     public string Key { get; set; }

     public Dictionary<string, string> Values { get; set; }
 }

I call the GetModelData method as follows,

row.GetModelData<DataModel>();
private static T GetModelData<T>(this RowModel row) where T : new()
{
    var data = new T();

    List<PropertyInfo> propertyList = typeof(T).GetProperties().ToList();

    PropertyInfo propertyDictionary = propertyList.Where(x => x.PropertyType.Name == typeof(Dictionary<string, string>).Name).FirstOrDefault();

    foreach (var cell in row.Cells)
    {
        if (propertyDictionary != null)
        {
             propertyDictionary.GetType().GetProperty("Item").SetValue(propertyDictionary, cell.X, new[] { cell.Y });
        }
    }

    return data;
}

I'm getting an error here because GetProperty("Item") returns null. But when I create an instance of Dictionary<string, string> and replace propertyDictionary, GetProperty("Item") is not return null and GetModelData method works. What is the difference between them? How can I set value to propertyDictionary?





mardi 25 janvier 2022

How to get all the public methods of a c++ subclass and put them in a vector?

I'm building a c++ aplication where the user create a class like that:

class MyClass : public FrameworkClass {
/** Some user attributes and methods
 * 
 */

class ROUTINE {
   private:
    void privateMethod();

   public:
    void method1();
    void foo();
    void AnyName();
}};

The idea is that all public methods of the ROUTINE subclass are executed on separate threads in a loop. Currently, the user himself has to register all the methods pushing them in a vector that the framework will iterate starting the threads, but I want to know if there is any way to make this process automatic, that is, create the array automatically since all the methods inside the ROUTINE subclass should always run this way, preferably in a non-intrusive way like a macro.

OBS:

the loop is something simple like:

void routineLoop() {
    while(Framework::IsRunning) {
        //call the method
    }
}

and it's alreandy working, the only problem it's the usability.





Scala reflection: how do I define a case class at runtime and then reference to it?

I would like to define a case class at run-time, like for example

val tb = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
val myClass: ClassDef = q"case class Authentication(email: String)".asInstanceOf[ClassDef]
val definedClass  = tb.define(myClass)

And then being able to refer to it in another reflection

  // Actor code that recognise the defined case object
  val actorCode = q"""
  import akka.actor._
  object HelloActor {
    def props() = Props(new HelloActor())
  }
  class HelloActor() extends Actor {
    def receive = {
      case $definedClass(emailParam)  => println("case object instance has been received!")
      case _       => println("None received!")
    }
  }
  return HelloActor.props()
  """

Any idea on how to do the trick ?





lundi 24 janvier 2022

How to use a Type variable to cast an object or instantiate a generic class? [duplicate]

Is it possible to do the following in C#?

Type myType = typeof(string);
var s1 = new List<myType>(); //s1 would be List<string>
var s2 = (myType) getObject(); //s2 would be string 

I've tried a bunch of ways but they all end up either eventually requiring T (for var myVar = (T) getObject(); or new List<T>(). I'm trying to do this without having any T. Only having the type info in a Type variable.





golang patch string values on an object, recursive with filtering

Community,

The mission

basic

Implement a func that patches all string fields on an objects

details

  • [done] fields shall only be patched if they match a matcher func
  • [done] value shall be processed via process func
  • patching shall be done recursive
  • it shall also work for []string, []*string and recursive for structs and []struct, []*struct

whats working

process strings on structs, if the object is passed via pointer

progress

see code below.
but this seems way too complicated

package main

import (
    "encoding/json"
    "fmt"
    "pmi.at/log"
    "pmi.at/str"
    "reflect"
    "strings"
)

type SOTag struct {
    Name    string  `process:"yes"`
    NamePtr *string `process:"yes"`
}

type SOUser struct {
    ID           int
    Nick         string
    Name         string    `process:"yes"`
    NamePtr      *string   `process:"yes"`
    Slice        []string  `process:"yes"`
    SlicePtr     []*string `process:"yes"`
    SubStruct    []SOTag   `process:"yes"`
    SubStructPtr []*SOTag  `process:"yes"`
}

func main() {
    fmt.Println("try to update string values of a struct via reflection")
    var NamePtr string = "golang"
    testUser := SOUser{
        ID:      1,
        Name:    "lumo",
        NamePtr: &NamePtr,
        SubStruct: []SOTag{SOTag{
            Name: "go",
        },
        },
        SubStructPtr: make([]*SOTag, 0),
    }

    err := patch( // struct to patch
        &testUser,
        // filter - true -> all fields that are strings
        func(idx int, v reflect.Value) bool {
            prefix := "-"
            matches := hasTag(v.Type().Field(idx), "process", "yes")
            if matches {
                prefix = "+"
            }
            fmt.Printf("MATCHER: [%s] %v k:%v t:%v - tag `process:'yes'`\n", prefix, v.Type().Field(idx).Name, v.Field(idx).Kind(), v.Field(idx).Type())
            return matches
        },
        // matcher
        func(in string) string {
            return fmt.Sprintf("!%s!", strings.ToUpper(in))
        })
    if err != nil {
        panic(err)
    }
    fmt.Println("Output:")
    fmt.Println(Stringify(testUser))
}

// patch shall accept i and &i and patch all fields (or *field) recursive via matcher...
func patch(i interface{}, matches func(idx int, v reflect.Value) bool, process func(s string) string) error {
    v := reflect.ValueOf(i)

    // if its a pointer, resolve its value
    if v.Kind() == reflect.Ptr {
        //v = reflect.Indirect(v)
        v = v.Elem()
    }

    // should double-check we now have a struct (could still be anything)
    if v.Kind() != reflect.Struct {
        return fmt.Errorf("unexpected type: %v", v.Kind())
    }
    for idx := 0; idx < v.NumField(); idx++ {
        f := v.Field(idx)
        if matches(idx, v) {
            n := v.Type().Field(idx).Name
            t := f.Type().Name()
            switch f.Kind() {
            case reflect.String:
                fmt.Println("KIND String -> Done?")

                value := f.Interface().(string)
                fmt.Printf("    [READ] Name: %s  Kind: %s  Type: %s Value: %v\n", n, f.Kind(), t, value)
                processedValue := process(f.Interface().(string))
                fmt.Printf("    [PATCH] Name: %s  Kind: %s  Type: %s Value: %v\n", n, f.Kind(), t, processedValue)
                //fmt.Printf("  write the value back - but how??: %v", processedValue)
                setValue(i, n, processedValue)
                fmt.Printf("    [WROTE] %v\n", f.Interface())
            //case reflect.Struct:
            //  fmt.Println("CALL Struct -> REFLECT RECURSIVE")
            //case reflect.Array: ?? equal slice?
            case reflect.Slice:
                fmt.Println("   KIND Slice -> Done(TODO:test)")
                slice := reflect.ValueOf(t)
                typ := reflect.TypeOf(f.Interface()).Elem()

                fmt.Printf("        XXX KIND Slice[]%s\n", typ)
                switch typ.Kind() {
                case reflect.String:
                    for i := 0; i < slice.Len(); i++ {
                        fmt.Println("           *** slice.Index(i) -> ", slice.Index(i))
                        value := f.Interface().(string)
                        fmt.Printf("    [READ] Name: %s  Kind: %s  Type: %s Value: %v\n", n, f.Kind(), t, value)
                        processedValue := process(f.Interface().(string))
                        slice.Index(i).SetString(processedValue)
                    }
                case reflect.Ptr:
                    // remove pointer and process
                    // this seems way too complicated... is there a better way???
                case reflect.Struct:
                    for i := 0; i < slice.Len(); i++ {
                        fmt.Println(slice.Index(i))
                        patch(slice.Index(i), matches, process)
                    }
                }

            case reflect.Ptr:
                fmt.Println("   KIND Ptr -> REFLECT RECURSIVE")
                fmt.Printf("        f.Type() -> %v\n", f.Type())               // prints **Foo
                fmt.Printf("        f.Type().Kind() -> %v\n", f.Type().Kind()) // prints **Foo
                //fmt.Println(" val:", val)
                //patch(val.Interface(), matches, process)
                switch f.Type().Kind() {
                default:
                    // implement for struct -> recursion
                    fmt.Printf("        TYPE %s (not implemented yet) -> REFLECT RECURSIVE\n", f.Type().Kind())

                }
            case reflect.Int:
            case reflect.Int8:
            case reflect.Int16:
            case reflect.Int32:
            case reflect.Int64:
            case reflect.Uint:
            case reflect.Uint8:
            case reflect.Uint16:
            case reflect.Uint32:
            case reflect.Uint64:
            case reflect.Uintptr:
            case reflect.Bool:
            case reflect.Float32:
            case reflect.Float64:
            case reflect.Func:
            case reflect.Chan:
            case reflect.Complex64:
            case reflect.Complex128:
            case reflect.UnsafePointer:
            case reflect.Interface:
            case reflect.Invalid:
                fmt.Printf("    KIND %s (skip)\n", f.Kind())
            default:
                // implement for struct -> recursion
                //TODO: Array
                //TODO: Map
                fmt.Printf("    KIND %s (not implemented yet) -> REFLECT RECURSIVE\n", f.Kind())
            }
        }
    }
    return nil
}

func Stringify(i interface{}) string {
    s, _ := json.MarshalIndent(i, "", " ")
    return string(s)
}

func hasTag(typeField reflect.StructField, tagName string, tagValue string) bool {
    tag := typeField.Tag
    if value, ok := tag.Lookup(tagName); ok {
        return value == tagValue
    }
    return false
}

//setValue
// @param i must be ptr
func setValue(i interface{}, fieldName string, newValue string) {
    log.Tracef("setValue on %v %v->%v", str.Stringify(i, false), fieldName, newValue)

    v := reflect.ValueOf(i)

    // if its a pointer, resolve its value
    if v.Kind() == reflect.Ptr {
        v = v.Elem()
    }

    if v.Kind() == reflect.Interface {
        v2 := reflect.ValueOf(v.Interface())
        v2.FieldByName(fieldName).SetString(newValue)
        return
    }

    // should double-check we now have a struct (could still be anything)
    if v.Kind() != reflect.Struct {
        log.Fatalf("unexpected type: %v", v.Kind())
        //return
        v = v.Elem()
    }

    // exported field
    f := v.FieldByName(fieldName)
    if f.IsValid() {
        // A Value can be changed only if it is
        // addressable and was not obtained by
        // the use of unexported struct fields.
        if f.CanSet() {
            // change value of N
            if f.Kind() == reflect.String {
                f.SetString(newValue)
            }
        }
    }
}




Reflection: Get values from Scanned Class with Annotation

So Im trying to get the file with the searched annotation, like this:

package com.nikita.Nikitos;

import java.util.Set;

import org.reflections.Reflections;

public class Main {

    public static void main(String[] args) {
        Reflections reflections = new Reflections("com.nikita.Nikitos");
        Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(lombok.Getter.class);
        System.out.println(annotated);

}
}

Im sure that my codes finds the file in which the annotation is located. Because I get following output in my console:

Reflections took 138 ms to scan 1 urls, producing 1 keys and 1 values

So there has to be a value. But my List that Im trying to print out is empty. So how do I get these values?

The file that contains the annotation looks like this:

package com.nikita.Nikitos;

import lombok.Getter;

@Getter
public class App
{
    int zahl;
    public App (int zahl) {
        zahl = this.zahl;
    }


}

Any suggestions?





dimanche 23 janvier 2022

Insert code into a method - Java JDK17, javassist [closed]

So I wanted to modify the code on-the-fly, and found this question with this answer. This is exactly what I needed, beside of being 12 years old and not working in JDK17 (well... reality of 2022).

I am bit green on Deep Reflection in Java, so it took me a while to even make this code working Today. If you feel the same about yourself, let me save you a couple of hours with this short introduction.

In JDK16 (and above) it is illegal to have fun (as is well explained here)...

...unless you run your program with:

--add-opens java.base/java.lang=ALL-UNNAMED
(You may or may not need this parameter, just keep it in mind)

And what is in java.base you can read here.

Now having some chance to run it, let see the code

In short, the code adds a Set that is updated every time the setter is called. Before you read the code, as being as green as me, I recommend you to read the comments first.

Comments

First and foremost: DO NOT load the class before modifications! rewritePersonClass(); is the first thing that happens in the code. When you load a class the game is over! (a sort of). So no new Person(), not even Person.class, in the code. When the class is loaded, only the GC (Garbage Collector) can get rid of it. That means, the modified class cannot replace it (at least not with the current ClassLoader). This answer, this and this may be useful while changing the ClassLoader.

Look here: CtClass ctPerson = pool.get("Person"); It is so tempting to write Person.class.getName(). But what did I write above? No class touching!

So the class is modified, loader did not see it before, let's load the new class. This line ctPerson.toClass(); is where the modified class should be loaded. But it is not working anymore (as of javassist 3.28.0-GA).

To make it working, you need to use: ctEntity.toClass(Class<?> neighbor);. Sweet, but who is the neighbor? You may ask.

The neighbor is a class that lives in the same namespace as the class you modify, but of course, you must not care about it, as it will be loaded (see above).

public class Neighbor // the Neighbor of Person...
{
}

So finally we can move on: ctEntity.toClass(Neighbor.class);

The code (Copied from the answer)

public class Person {

    private String firstName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

public static void rewritePersonClass() throws NotFoundException, CannotCompileException {
    ClassPool pool = ClassPool.getDefault();
    CtClass ctPerson = pool.get("Person");
    CtClass ctSet = pool.get("java.util.LinkedHashSet");

    CtField setField = new CtField(ctSet, "updatedFields", ctPerson);
    ctPerson.addField(setField, "new java.util.LinkedHashSet();");

    CtMethod method = ctPerson.getDeclaredMethod("setFirstName");
    method.insertBefore("updatedFields.add(\"firstName\");");

    ctPerson.toClass();
}


public static void main(String[] args) throws Exception {
    rewritePersonClass();

    Person p = new Person();
    p.setFirstName("foo");

    Field field = Person.class.getDeclaredField("updatedFields");
    field.setAccessible(true);
    Set<?> s = (Set<?>) field.get(p);

    System.out.println(s);
}

I hope it worked for you and gave you a kick-start into Java's Deep Reflection.





Can I mark a field as inaccessible within a Java class (the defining class itself)?

In a JNI environment, I want my Java class to contain some private fields, which I want to explicitly mark as "off limits" for Java access, so only my native code can use them.

So basically I have

public class Example() {
   private int var;
   private int varInternalState;

   public native void nativeMethod(...);
   public void otherMethod() { ... }
}

nativeMethod() needs some internal state information per object, which I want to keep in varInternalState. (I know how to do this; it works). But I want to mark varInternalState as "off limits" for otherMethod(), because it makes absolutely no sense to access it from Java, and I want to get a compiler error - or at least warning - if my future self or someone unfamiliar with the code acidentially reads or writes it.

Declaring it private doesn't help, because this is about accesses from the class itself, not from other classes.

And because of some Reflection magic, I don't want to give a name like doNotEverTouchThis to the internal variable; I'd like to stay free in naming that thing.

I think there's no keyword in Java to do this as I can't explicitly mark fields as synthetic, so I guess Annotations might help - however, I know next to nothing about them, and I don't want to reinvent the wheel if possible.

So, is there a clever way to declare varInternalState, or an existing annotation library that lets me do something like @Inaccessible private int varInternalState, which makes the compiler spit an error whenever I try to read/write the field?





Haskell Beginner, Calling Functions by their Names

Trying the 99 puzzles to learning Haskell. A quality-of-life problem that I have is that every time I test a solution, I would write a function:

mySolutionForQuestion12 :: someFunctionType

testMySolutionForQuestion12 :: IO ()
testMySolutionForQuestion12 = do
    print "testMySolution"
    print $ mySolutionForQuestion12 "myInput1"
    print $ mySolutionForQuestion12 "myInput2"
    putStr "\n"

main = do
    -- neglected code to test solutions for question 1 up to 11 --
    testMySolutionForQuestion12
    ...

    -- instead I want to do something like --
    callAllFunctionsInThisFileByNameBeginningWith "test"
    -- , so that I only have to write one line of code instead of n lines --

To be able to be as lazy as possible, I would love to have a way to make my main automatically call all functions that begin with the 4 exact characters test in my .hs file.

Is this possible in Haskell? Coming from Python, for Python a dynamic language this is self evident, but for C or C++ this would need quite a workaround (I don't actually know how to do that in these languages)

I am wondering thus how would Haskellians (if this is a word?) approach this? Is there some "best practice" in this regard?





samedi 22 janvier 2022

[Protobuf3-C++]How to unpack a field of Any with reflction?

My proto file looks like this:

message HqMessage {
    uint32 busi_no          = 1;
    google.protobuf.Any detail      = 2;
}

message B0T4F1 {
    uint32 MarketType               = 501;
}

//---------------------------------------------------------------------

STEP1, use protobuf's reflection, I had set the message of BOT4F1 to the 'detail':


const google::protobuf::Descriptor* _detail_des = _des_pool->FindMessageTypeByName("B0T4F1");
const google::protobuf::Message* _detail_prototype_message = m_dynamic_factory.GetPrototype(_detail_des);
google::protobuf::Message* _detail_msg = _detail_prototype_message->New();
const google::protobuf::Reflection* _detail_msg_ref = _detail_prototype_message->GetReflection();
const google::protobuf::FieldDescriptor* _detail_fd = _detail_des->FindFieldByNumber(501);
uint32 mkt_type =100;
_fd = _des->FindFieldByNumber(2);
_msg_ref ->**SetAllocatedMessage**(_msg, _detail_msg, _fd);

STEP2,serialize the message to a buffer, then parse the HqMessage from the buffer.

STEP3, first, I get the message of Any, then serialize the any message to buffer again. Finally,get the message object of B0T4F1 through the new buffer.

How can i parse the buffer to the message of B0T4F1 without serialize ’detail' message again. Could I get the ‘B0T4F1' message from 'HqMessage ' directly? How can i do this?





How to implement C# Reflection code in Python?

I am working on a test automation project that requires the use of reflection with a keyword driven framework. I am having trouble finding Python equivalents for C# methods.

Type t = Type.GetType(FullPathForReflection + Page);
PropertyInfo getPropInfo = t.GetProperty(Object);
var createdClassInstance = Activator.CreateInstance(t, AppiumSession);
WindowsElement getObjectProp = (WindowsElement) getPropInfo.GetValue(createdClassInstance);
keywordClass.processKeywords(Keyword, getObjectProp, Value);

I'm using type() to replace Type.GetType() but can't find any equivalents for GetProperty(object) or GetValue(). Also, I am using t() as a replacement for Activator.CreateInstance and that seems to work.

If anyone could help me find replacement methods or equivalents that would be amazing! Thank you!





vendredi 21 janvier 2022

PathAssemblyResolver and MetadataLoadContext - can they work in Blazor Webassembly?

We have some Reflection utilities that rely heavily on the MetadataLoadContext and PathAssemblyResolver classes (they enable us to analyze the types without incurring in the full cost of loading the full assembly into the execution context).

We have tried using them (client-side) from a Blazor WebAssembly App.

We are having difficulty specifying the paths to the PathAssemblyResolver class (we know the target DLLs are there, but they don't seem to be accessible via the sandboxed filesystem). Is there a way where we could coax the PathAssemblyResolver to locate the DLLs?

We know that as a workaround, the analysis could be performed on the server side, but are very interested in learning the possibilities as well as the limitations of Blazor WebAssembly technology.





Dynamically use Type for a method in Generic

I have many Schemas as below:

public class Schema1 
{
   public string prop1 {get; set;}
   public int prop2 {get; set;} 
}

public class Schema2 
{
   public DateTime prop3 {get; set;}
   public bool prop4 {get; set;} 
}

Now I want to dynamically get their type and call below method where T is Schema1 or Schema2 and so on. Below method returns objects of T i.e. List, List, List... so on. Below I am passing Type as well in parameter but confused how to use it.

public static List<T> Method1(string param1, out SchemaError[] errors, Type type)
{
List<T> list = new List<T>();   
// other Operations
list = JsonConvert.DeserializeObject<List<T>>(string);
return list;
}

How can I approach this problem? Is there any way through Interface or any design pattern to separate out schemas? I know there is a way through reflection

MethodInfo method = typeof(ClassName).GetMethod(nameof(MethodName));
MethodInfo generic = method.MakeGenericMethod(schemaType);
return generic.Invoke(Activator.CreateInstance(typeof(ClassName)), new object[] { param1 });

but there are some limitations with reflection approach.





[Scala Toolbox]: Compile a Case Class at run-time and then instantiate it

I'm trying to define a case class using Scala Reflection Toolbox and to instantiate it. What is the best way to do it?

At the moment I do

val codeToCompile = q"""case class Authentication(email:String)"""
val tree = toolbox.parse(codeToCompile) 
val classDefinition : ClassDef = tree.asInstanceOf[ClassDef]
val definedClass = toolbox.define(classDefinition)

I would like to use the constructor of the case class to instantiate it at run-time after I have defined it into the Toolbox, Like

val codeToCompile = q"""val myAuth = Authentication("test@gmail.com")"""
val tree = toolbox.parse(codeToCompile)
val binary = toolbox.compile(tree)()

I get the error: Authentication not found ... How can I do it ?





mercredi 19 janvier 2022

Get passed Annotation Parameters from Field Annotations

I have two annotations, this class one:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Processor {
  public String description() default "";
}

And also this Field one:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ProcessorParameter {
    public String name() default "";
    public String value() default "";
    public String[] range() default {};
    public String description() default "";
}

They both are getting used in a class like this one:

    @Processor(description = "blabla")
    public class Prozessor1{
        @ProcessorParameter(description = "test3")
        public int parameter1;
        @ProcessorParameter(description = "test4")
        public int parameter2;
        @ProcessorParameter(description = "test5")
        public int parameter3;
    }

I have different classes of the Prozessor and I want to be able to access all the parameters of the Prozessor and ProcessorParameter Annotation.

Right now I am using this code:

public static void main(String[] args) {
        Reflections ref = new Reflections();
        for (Class<?> cl:
                ref.getTypesAnnotatedWith(Processor.class)){
            Processor processor = cl.getAnnotation(Processor.class);
            System.out.printf("Found class: %s, with meta name: %s%n",
                    cl.getSimpleName(),processor.description());
            for(Field field : cl.getFields()) {
                System.out.printf("Found parameter: %s and %s%n",
                        field.getName(), field.getName());
            }
        }
    }

Right now I am getting this as a result:

Found class: Prozessor1, with meta name: blabla
Found parameter: parameter1 and parameter1
Found parameter: parameter2 and parameter2
Found parameter: parameter3 and parameter3

I obviously do not need the second field.getName() but I want to access the passed ProcessorParameter description ("test3"/"test4"/"test5") but I do not know how to access this.





mardi 18 janvier 2022

How to get all the fields which is annotated by my custom annotation?

I customed a field annotation to annotate the field which I want to it multiplied by scale.

I'm wandering is there a better way to get annotated fields, instead of iterating over all the fields.

It's my code below:

custom annotation:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface ShowScale {
    String scale();
}

Java object (the map is the matter):

class Vo {
    @ShowScale(scale = "0.8")
    private BigDecimal member1 = BigDecimal.ZERO;
    @ShowScale(scale = "0.8")
    private BigDecimal member2 = BigDecimal.ONE;
    @ShowScale(scale = "0.8")
    private BigDecimal member3 = BigDecimal.TEN;

    private String otherMember = "leave me alone";

    //this map is the matter...
    private Map<String, List<InnerVo>> map;

    public static class InnerVo {
        @ShowScale(scale = "0.8")
        private BigDecimal innerMember1 = BigDecimal.ZERO;
        @ShowScale(scale = "0.8")
        private BigDecimal innerMember2 = BigDecimal.ONE;
        private String otherMember = "leave me alone";

        @Override
        public String toString() {
            return new ToStringBuilder(this)
                    .append("innerMember1", innerMember1)
                    .append("innerMember2", innerMember2)
                    .append("otherMember", otherMember)
                    .toString();
        }
    }

    public Vo() {
        HashMap<String, List<InnerVo>> map = new HashMap<>();
        ArrayList<InnerVo> list = new ArrayList<>();
        list.add(new InnerVo());
        list.add(new InnerVo());
        list.add(new InnerVo());
        ArrayList<InnerVo> list1 = new ArrayList<>();
        list1.add(new InnerVo());
        list1.add(new InnerVo());
        list1.add(new InnerVo());
        ArrayList<InnerVo> list2 = new ArrayList<>();
        list2.add(new InnerVo());
        list2.add(new InnerVo());
        list2.add(new InnerVo());
        map.put("key", list);
        map.put("key1", list1);
        map.put("key2", list2);
        this.map = map;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("member1", member1)
                .append("member2", member2)
                .append("member3", member3)
                .append("otherMember", otherMember)
                .append("map", map)
                .toString();
    }
}

My implement:

public class ClassTest {
    public static void main(String[] args) throws Exception {
        Vo vo = new Vo();
        System.out.println("before----->:" + vo);
        handle(vo);
        System.out.println("after----->:" + vo);
    }

    /**
     * All the fields (include in map and list) annotated by @ShowScale
     * should be multiplied by scale.
     *
     * @param obj
     */
    private static <T> void handle(T obj) {
        try {
            Class<?> clz = obj.getClass();
            String className = clz.getName();
            System.out.println("\n-------> objType:" + className);

            if (className.contains("java.util.ArrayList")) {
                for (Object o : (List) obj) {
                    handle(o);
                }
            } else if (className.contains("java.util.Map")) {
                Map map = (Map) obj;
                map.forEach((key, value) -> {
                    System.out.println(key + " :" + value);
                    handle(value);
                });
            } else {
                for (Field f : clz.getDeclaredFields()) {
                    String typeName = f.getType().getTypeName();
                    if (f.isAnnotationPresent(ShowScale.class)) {
                        f.setAccessible(true);
                        BigDecimal o = (BigDecimal) f.get(obj);
                        System.out.println("o = " + o);

                        BigDecimal scale = new BigDecimal(f.getAnnotation(ShowScale.class).scale());
                        f.set(obj, o.multiply(scale).setScale(2, RoundingMode.HALF_UP));

                    } else if (typeName.contains(Map.class.getName())) {
                        f.setAccessible(true);
                        Map map = (Map) f.get(obj);
                        map.forEach((key, value) -> {
                            System.out.println(key + " :" + value);
                            handle(value);
                        });
                    } else if (typeName.contains(List.class.getName())) {
                        f.setAccessible(true);
                        for (Object o : (List) f.get(obj)) {
                            handle(o);
                        }
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

thank you for any tips :)





How to determine that a class implements a specific interface with self-referencing, generic constraints?

I have a DbContext-derived class and want to get a list of all DbSet<Entity> properties whose generic argument Entity matches the following criteria:

  • Entity must not inherit from a class.
  • Entity must implement the interface IEntity.
  • Entity must implement the interface IEntity<TEntity> where TEntity has the following constraints:

where TEntity : class, IEntity, IEntity<TEntity>, new()

The second-last line in the code below attempts to do that but fails. Furthermore, I do not know how to express constraint checks at runtime.

The property DbSet<Employee> should pass the check whereas DbSet<Department> should not.

namespace DomainBuilder
{
    internal static class Program
    {
        private static void Main (string [] args)
        {
            var dbSetProperties = typeof (DomainBuilder.DomainBuilderContext)
                .GetProperties (BindingFlags.Instance | BindingFlags.Public)
                .Where (p => p.CanRead && p.CanWrite)
                .Where (p => p.GetGetMethod (nonPublic: false) != null)
                .Where (p => p.GetSetMethod (nonPublic: false) != null)
                .Where (p => (p.PropertyType.Name.StartsWith (nameof (DbSet<DomainBuilder.IEntity>))))
                .Where (p => (p.PropertyType.IsGenericType))
                .Where (p => (p.PropertyType.GenericTypeArguments.Length == 1))
                .ToList();

            foreach (var dbSetProperty in dbSetProperties)
            {
                Console.WriteLine ($@"DbSet<{dbSetProperty.PropertyType.GenericTypeArguments [0].Name}>: {DomainBuilder.DomainBuilderContext.ImplementsIEntityGenericWithConstraints (dbSetProperty)}.");
            }
        }
    }

    public interface IEntity
    {
        public long Id { get; set; }
        public DateTime DateTimeCreated { get; set; }
        public DateTime DateTimeModified { get; set; }
    }

    public partial interface IEntity<TEntity>: IEntity
        where TEntity : class, IEntity, IEntity<TEntity>, new()
    { }

    public partial class Employee: IEntity<Employee>
    {
        public long Id { get; set; }
        public DateTime DateTimeCreated { get; set; }
        public DateTime DateTimeModified { get; set; }

        public long? DepartmentId { get; set; }
        public Department? Department { get; set; }
    }

    public partial class Department: IEntity
    {
        public long Id { get; set; }
        public DateTime DateTimeCreated { get; set; }
        public DateTime DateTimeModified { get; set; }

        public string Name { get; set; } = "";
    }

    public partial class DomainBuilderContext: DbContext
    {
        public virtual DbSet<Employee>? Employees { get; set; }
        public virtual DbSet<Department>? Departments { get; set; }

        public static bool ImplementsIEntityGenericWithConstraints (PropertyInfo dbSetProperty)
        {
            var typeDbSet = dbSetProperty.PropertyType; // DbSet<Employee>.
            var typeEntity = typeDbSet.GenericTypeArguments [0]; // Employee.

            if (typeEntity.BaseType != typeof (object)) { return (false); }

            var interfaces = typeEntity.GetInterfaces();

            // Works fine.
            var isIEntity = interfaces.Any (i => i == typeof (IEntity));

            // How to ensure that [typeEntity] implements [IEntity<TEntity>]
            //  where TEntity: class, IEntity, IEntity<TEntity>, new().
            var isIEntityGeneric = interfaces.Any (i => i == typeof (IEntity<>));

            return (isIEntity && isIEntityGeneric);
        }
    }
}




ParameterExpression of type 'Data' cannot be used for delegate parameter of type 'System.Object'

i'm trying to write a function that checks the methods with a specific attribute and collects info about them. Then, i need to compile them into expression so it's overhead will be minimal. But when i try to run my function, i get error that i put into the header.

My code is:

MethodInfo? method_info = handler_class.GetType().GetMethod("Handler");
if (method_info == null) continue;
ParameterInfo[] prms = method_info.GetParameters();
Type param_type = prms[0].ParameterType;

ParameterExpression[] prm_exprs = new ParameterExpression[] { 
    Expression.Parameter(param_type, "data")
};
MethodCallExpression method_expression = Expression.Call(
    Expression.Constant(handler_class),
    method_info,
    prm_exprs
);

Debug.WriteLine(method_expression.ToString());

Expression<Action<object>> le = Expression.Lambda<Action<object>>(
    method_expression,
    "HandlerCaller",
    true,
    prm_exprs
);
Action<object> handler = le.Compile();




lundi 17 janvier 2022

Dynamic enum with OpenJDK 11 using reflection

I'm working on a project running with JDK8 and we want to migrate it to OpenJDK11.

But, there is legacy code that creates enums dynamically at runtime (using reflection and sun.reflect.* packages) :

enumClass.cast(sun.reflect.ReflectionFactory.getReflectionFactory().newConstructorAccessor(constructor).newInstance(params));

Or

    // before, field is made accessible, the modifier too
    sun.reflect.FieldAccessor fieldAccessor = sun.reflect.ReflectionFactory.getReflectionFactory().newFieldAccessor(field, false);
    field.set(target, value);

Unfortunately, sun.reflect.* classes are no longer available in OpenJDK11.

I've tried using jdk.internal.reflect.ConstructorAccessor but I'm getting the error java: package jdk.internal.reflect does not exist. And I don't think it's a good idea to rely on jdk.internal.* classes.

Is there any OpenJDK11 alternative to create enums at runtime ?





Filter out object from a certain namespace

I have a List<BaseType> objects that I need to work with.

For most derived types, what I do works perfectly, but for some reason, certain derived types from a certain namespace don't work well (unsolvable problem regarding external libraries).

Is there a way I can filter out all objects from that namespace?





dimanche 16 janvier 2022

Automapper throwing System.Reflection.AmbiguousMatchException: Ambiguous match found

I have a piece of code that throws exception and I dont quite understand why.

 public  async Task<List<CategoryVm>> Handle(GetCategoriesListQuery request, CancellationToken cancellationToken)
    {
        var categories = (await _categoryRepository.ListAllAsync()).OrderBy(x => x.Name);
      //  var list = categories.ToList();
        return _mapper.Map<List<CategoryVm>>(categories);
    }

enter image description here

I managed to get around problem as below. Would be be nice know why this works.

  public  async Task<List<CategoryVm>> Handle(GetCategoriesListQuery request, CancellationToken cancellationToken)
    {
        var categories = (await _categoryRepository.ListAllAsync()).OrderBy(x => x.Name);
        var list = categories.ToList();
        return _mapper.Map<List<CategoryVm>>(list);
    }

Category and CategoryVm

public class CategoryVm
{
    public Guid CategoryId { get; set; }
    public string Name { get; set; } 
}
public class Category: AuditableEntity
{
    public Guid CategoryId { get; set; }
    public string Name { get; set; }
    public ICollection<Event> Events { get; set; }
}




samedi 15 janvier 2022

Reading custom annotation for JUNIT

I have a custom annotation which I use as config to start off one time set-up for Junit.

@Target(TYPE) @Retention(RUNTIME)
public @interface MyAnnotation{
   String host();
   int port();
}

Test class:

@MyAnnotation(host="0.0.0.0", port=4567)
public class MyTest extends MyAbstractClass{
   @Test
   public void myTest(){
      //do testy things
   }   
}

Superclass:

public class MyAbstractClass{

   @BeforeAll
   public static void start(){
    Config cfg = readConfig();
    //Use config to do one time set-up
   }

   private static Config readConfig(){
      MyAnnotation ann = MyTest.class.getAnnotation(MyAnnotation.class);
      return new Config(ann.host(), ann.port());
   }
}

So currently, I hardcode the name of the test class (MyTest) in readConfig(..). This won't work when I add a second test class.

One way to solve it is:

  • Add another @BeforeAll method in MyTest which will call the @BeforeAll in super-class and pass the class name as a param.

However, I am curious if I can read the name of the executing subclass in the superclass via some reflexion magic. Any ideas are most welcome.

Thanks





Reflection: Create instance of a class that inherit from another class located in sperate assembly

I created an empty Web Form Application and Created a WebForm and a class named MyClass:

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public string GetText()
        {
            return "Message of Web Form 1";
        }
    }
}

and:

namespace WebApplication1
{
    public class MyClass
    {
        public string GetText()
        {
           return "Message from MyClass";
        }
    }
}

and I publish it using "Merge all assemblies in one assembly" option:

enter image description here

and then I want to get type and then create instance of WebForm1 and MyClass. So I wrote this code:

Assembly asm = Assembly.LoadFrom(@"C:\Pub\bin\WebApplication1.dll");

Type tMyClass = asm.GetType("WebApplication1.MyClass");

Type t = asm.GetType("WebApplication1.WebForm1"); <----Error

after the code has been ran tMyClass has correct type:

enter image description here]

but when it want to get type of WebForm1 it generate an error:

enter image description here

System.TypeLoadException: 'Could not load type 'System.Web.UI.Page' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.'

How can I get type of WebForm1 and create instance of it?





vendredi 14 janvier 2022

Can an `ElementVisitor` be used to traverse the statements in the body of a method?

I'm trying to make a custom annotation that checks to see if a certain method is called in a method's body annotated with it. Something like:

@TypeQualifierDefault(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
@interface MutatingMethod {
}

interface Mutable {
  void preMutate();
  void postMutate();
  // other methods
}

And then within a certain Mutable class we would have:

class Structure<T> implements Mutable {
  @MutatingMethod
  void add(T data) {
    preMutate();
    // actual mutation code
    postMutate();
  }
}

I want to be able to get warnings of some sort if the body of a method like add that is annotated with @MutatingMethod does not include calls to preMutate and postMutate. Can an ElementVisitor (javax.lang.model.element.ElementVisitor) be used to traverse the (possibly obfuscated) statements and method calls in the body of a method? If so what would that look like? If not what else can I use?

Just to clarify, I know this is impossible (or more difficult) to accomplish in runtime via bytecode decompilation, so this annotation is meant to only work during compilation via reflection (java.lang.reflect.* and javax.lang.model.*) and is not retained in class files.

You are free to modify the code however you want to get it to work, for example by introducing a new annotation called @MutableType that Structure and any other Mutable types must be annotated with it for this to work.

A cherry on top would be to assert that preMutate is called before postMutate and not after.

It shouldn't matter but I'm using Gradle and the IntelliJ IDEA IDE.

Any help is greatly appreciated; material on this is strangely scarce and/or inadequate on the web. I have been using publicly available sources to learn about this!





Is there a way of identifying if a given class has any references to another class?

I can work through the hierarchy with reflection, yes, but it is challenging, because the elements are diverse. So:

class A
{
    string Hello;
}

class B
{
    List<A> Hellos;
}
class D:B
{
   A randomthing;
}

class C:D
{
    string OtherThing;
}

I have an object that is of type C, and I want to be able to find and identify that this has, down the line, a list of A object, and then to process them.

The real life example is a more complex hierarchy than this, of course, but the principle is the same. I have tried a recursive loop through the properties, but I was struggling to find ways of dealing with a) not trying to process string and int objects and b) identifying that a property was something like an enumerable of X. Related is the fact that there might be enumerables of classes that inherit from A.

If anyone can suggest an approach that would make this straightforward, that would be appreciated. I need to be able to do this in a range of places, so I have to be able to start with any class type.

So I start with a type of x. In this case x is C, but x could just as easily be Z, with no links to type A.

Also, this needs to pick up whether I have class D in or not. I want to be able to pick up Hellos and randomthing.





[Akka]: Spawn an Actor at runtime with Scala Reflection and monitor its behavior using Grafana and Prometheus

I set up Grafana and Prometheus in Akka to monitor the behaviour of my system. If I spawn Actors at compile time it works and I can see them on the dashboard.

Now I'd like to compile an Actor at runtime and monitor its behaviour. In order to achieve that, I run

  val toolbox = currentMirror.mkToolBox()
  // Class instance
  val actorCode = q"""
  import akka.actor._
  object HelloActor {
   def props(name : String) = Props(new HelloActor(name))
  }
class HelloActor(myName: String) extends Actor {
  def receive = {
    case "hello" => println("hello from %s".format(myName))
    case _       => println("'huh?', said %s".format(myName))
  }
}
  return HelloActor.props("Jane")
"""

Then I compile the Actor, I get the Props and send a message to it in this way

  val compiledCode = toolbox.compile(actorCode)()
  val actorSystem = ActorSystem("firstActorSystem")
  val myProps = compiledCode.asInstanceOf[Props]
  val helloActor = actorSystem.actorOf(myProps)
  helloActor ! "hello"

Everything works fine, but if I go to the Prometheus dashboard I can not see the Actor instance and the messages that have been sent.

Any tips to solve this issue ?





How can I export all variable information at a breakpoint in idea IDE for java

I want to export every objects' field including nested fields at a breakpoint for comparison.

Now what I need to do is to click and expand all objects that have more fields. After that, I am finally able to ctrl-A and ctrl-C, i.e., copying everything. Therefore, my question is: is there a way to help export that information more quickly?

Attached is the debugger view in IDE.

idea debugging view





jeudi 13 janvier 2022

Use log4j to print variable name java

is it possible to print a variable name using log4j?

I want to achieve something like:

SomeObject someName = 123;

log.info("The variable: " + someName.getMyName() + " was used.");

and get result: The variable: someName was used.

ps I do not have access to the object.





How to list all ClassLoaders in JVM

Is there a way to get all ClassLoaders in JVM?... For instance:

ClassLoader[] list = ClassLoader.getAllClassLoaders();

Thanks a lot !





mercredi 12 janvier 2022

How to access class or record field with the name of the field as a string?

Say you have a record or class:

record R {
  var value: int;
}

How can I access the field value by using the string "value"?

For example, in Python, you can access fields using the getattr built-in:

class C:
    def __init__(self, val):
        self.value = val

c = C(2)

print(getattr(c, 'value')) # prints 2

What would this look like in Chapel?





mardi 11 janvier 2022

Can I use reflection to detect potential attack gadget vulnerabilities?

I use a package that contains code for a tcp server and client that is really easy to use, problem is it uses Newtonsoft Json serialization and deserialization with TypeNameHandling.All to send an receive messages, and client or servers could be untrusted sources.

public static JsonSerializerSettings JsonSettings = new()
        {
            TypeNameHandling = TypeNameHandling.All,

        };
[...]
[...]
return JsonConvert.DeserializeObject<INetMessage>(message.Substring(8), JsonSettings);

It also contains such a class:

public class NetMessage<T> : INetMessage where T: ISafeNetSerialization
    {
        public ulong snowflake { get; set; }

        public T Content { get; set; }

        public NetMessage(T content)
        {
            this.Content = content;
        }

        public override string ToString()
        {
            return Content.ToString();
        }
    }

Can I use a code snippet using reflection, to go through all types inheriting INetMessage and ISafeNetSerialization interfaces and check if they can possibly contain something (or contain something that contains... etc) like an object, a dynamic or an Exception, a CollectionBase and other untyped objects and collections, including any Generic types inheriting those two that could be added in another library ?

I know that I should especially look for TempFileCollection and ObjectDataProvider.

Code snippet would then be used inside an unit test or at runtime before the initialization of the first server / and / or tcp client.





lundi 10 janvier 2022

List all defined functions in python file (without module) with their argument names

I've made a bunch of helper functions for some data analysis work, but overtime that "bunch" has grown to quite a lot of functions. To use them, I have a huge ugly if-else branching logic for various command line arguments, but it gets tedious to maintain, as well as being annoying to have to add to the branching everytime I add a new function.

As such, I'd like to be able to make all functions that follow a certain naming schema, namely not starting with an underscore, callable via command line. To do so, I need to be able to dynamically know what functions exist, as well as what arguments they require.

Is there an easy way to do so? I saw some post on stackoverflow using an inspect module, but that required the functions to be in a different module, which is not my case.

Thanks!





dimanche 9 janvier 2022

How to implement logic for annotation Java?

Assume I have class Laptop and its annotated with @ProcessorConstraint It is Java code without any frameworks. In Spring Framework you can implement custom annotation, then you create annotation handler class, that is implicitly handles your annotated fields/classes, etc. But how can I do that implicitely with Java only?

Now I have code, that checks "If class annotated - check field for nullable":

public static void main(String[] args) {
        Laptop laptop = new Laptop("Scissor keyboard");
        System.out.println(laptop);


        validateLaptop(laptop);
        laptop.setProcessor("Intel 7");
        validateLaptop(laptop);
    }

    private static void validateLaptop(Laptop laptop) {
        boolean annotationPresent = laptop.getClass().isAnnotationPresent(ProcessorConstraint.class);
        if (annotationPresent) {
            if (laptop.getProcessor() == null) {
                throw new RuntimeException("Processor must not be null");
            }
        }
    }

But it is explicitly and I have to check each object for that. What should I do to avoid this?





samedi 8 janvier 2022

why foreach loop seems to be much faster in second or third run?

I was testing the performance difference between reflection lib(e.g.fasterflect) against setting it manually. It is not surprising that reflection lib to be slower than manually set to value in code, however, on my laptop, following loop becomes much faster to run from second or third run:

var list = new List<ESG_MSCI_ClimateChange>();
///add 1million objects in the list first
for (int i = 0; i <= 1000000; i++)
{
    var a = new ESG_MSCI_ClimateChange();
    var b = (IExchangeForESG_MSCI_ClimateChange)a;
    b.CarbonEmissionsEvicScope1Inten = (decimal)120;
    b.CarbonEmissionsEvicScope2Inten = (decimal)120;
    b.CarbonEmissionsScope12Fy20 = (decimal)120;
    b.CarbonEmissionsScope12IndustryIntensity = (decimal)120;
    b.CarbonEmissionsScope12Inten = (decimal)120;
    b.CarbonEmissionsScope12Inten3yavg = (decimal)120;
    b.CarbonEmissionsScope12IntenFy08 = (decimal)120;
    b.CarbonEmissionsScope12IntenFy09 = (decimal)120;
    b.CarbonEmissionsScope12IntenFy10 = (decimal)120;
    list.Add(a);
}
////loop these one million objects 4 times and output time 
for (var j = 0; j <= 3; j++)
{
    Console.WriteLine("start!");

    Stopwatch w = new Stopwatch();
    w.Start();
    foreach (var b in list)
    {
        b.CarbonEmissionsEvicScope1Inten = (decimal)120;
        b.CarbonEmissionsEvicScope2Inten = (decimal)120;
        b.CarbonEmissionsScope12Fy20 = (decimal)120;
        b.CarbonEmissionsScope12IndustryIntensity = (decimal)120;
        b.CarbonEmissionsScope12Inten = (decimal)120;
        b.CarbonEmissionsScope12Inten3yavg = (decimal)120;
        b.CarbonEmissionsScope12IntenFy08 = (decimal)120;
        b.CarbonEmissionsScope12IntenFy09 = (decimal)120;
        b.CarbonEmissionsScope12IntenFy10 = (decimal)120;
    }
    w.Stop();
    Console.WriteLine($"took {w.ElapsedMilliseconds}ms to set");
}

What I see is that for the first loop always take much longer, and the second test and later run will be much faster. But why is that? If I use reflection to set the value, the time taken is fairly consistent(similar to the time taken in the first run).

So is c# caching the result somehow when set properties manually, so I shouldn't run this several times if I want to compare the performance between manual value setting and reflection (as in real world, we won't set the same list again and again)? enter image description here





Question about how to use the java reflection API

The goal is to modify the value by accessing the private instance in the code below.

public class mySingleton5 {
//Double check lock


//Volatile stores Java variables in Main Memory and reads them from Main Memory, not r/w to CPU cache.
private volatile mySingleton5 instance;

private mySingleton5(){}
public mySingleton5 getInstance(){
    if(instance == null){ //Single tone class, locked transfer.
        synchronized (mySingleton5.class){
            if(instance == null){ //When you create an object,
                instance = new mySingleton5();
            }
        }
    }
    return instance;
}

}

In order to access the instrument, I wrote the reflection API code as below. In order to change the field value, you have to create the class object written above, but it is private, so you cannot create the object and hand it over to the first element of the set function.

    Class<mySingleton5> msclass = mySingleton5.class;
    System.out.println("Class name: "+msclass.getName());
    Class clazz2 = Class.forName("mySingleton5");
    Field fld = clazz2.getDeclaredField("instance");
    fld.setAccessible(true);
    fld.set("???", "123"); //error
    System.out.println(fld.get(msclass));

Is there any way to access fields of a private class?





vendredi 7 janvier 2022

Is there a better method to apply some operation on a group of properties?

Not sure this is the place for question like this, but give a try anyway. Say my web api is returning some really wide response (e.g. 900 properties), in the object, I have these:

public class WideOutput{
     public datetime Date1 {get;set;}
     public decimal Value1 {get;set;}
     ....
     public decimal Value20 {get;set;}
     public datetime Date2 {get;set;}
     public decimal Value21 {get;set;}
     ....
     public decimal Value40 {get;set;}
     public decimal SomeOtherValues {get;set;}
     public decimal SomeOtherValues860 {get;set;}
}

This is the requirement:

  1. For properties Value1 to Value20, apply exchange rate from Property Date1
  2. For properties Value21 to Value40, apply exchange rate from Property Date2
  3. For other properties, just output raw value.

Of course I could do this:

var output = SomeService.LoadWideOuput();
var exchangeRateFroDate1 = ExchangeService.GetRate(output.Date1);
var exchangeRateFroDate2 = ExchangeService.GetRate(output.Date2);
output.Value1 = output.Value1* exchangeRateFroDate1 
....
output.Value20 = output.Value1* exchangeRateFroDate20

output.Value21 = output.Value1* exchangeRateFroDate21 
....
output.Value40 = output.Value1* exchangeRateFroDate40 

However, that method will be really long and very boring to write.

Another way I can think of is using attribute and reflection. Something like this:

public class WideOutput{
     public datetime Date1 {get;set;}
     [ExchangeField(LinkedTo="Date1")]
     public decimal Value1 {get;set;}
     ....
     [ExchangeField(LinkedTo="Date1")]
     public decimal Value20 {get;set;}
     public datetime Date2 {get;set;}
     [ExchangeField(LinkedTo="Date2")]
     public decimal Value21 {get;set;}
     ....
     [ExchangeField(LinkedTo="Date2")]
     public decimal Value40 {get;set;}
     public decimal SomeOtherValues {get;set;}
     public decimal SomeOtherValues860 {get;set;}
}

Then in the method I could do this (pseudo code idea only):

var output = SomeService.LoadWideOuput();
var exchangeRateFroDate1 = ExchangeService.GetRate(output.Date1);
var exchangeRateFroDate2 = ExchangeService.GetRate(output.Date2);
var exchangeRateDate1Fields = ReadAttributesRelatedAndReturnPropertyList(typeof(output), "Date1");
SetPropertyValueUsingReflection(exchangeRateDate1Fields, output, exchangeRateFroDate1);
var exchangeRateDate2Fields = ReadAttributesRelatedAndReturnPropertyList(typeof(output),"Date2");
SetPropertyValueUsingReflection(exchangeRateDate2Fields , output, exchangeRateFroDate2 );

Technically it will work, but as I use reflection to set value, it certainly will be slower. In a web API environment, I do need to pay attention to performance.

I am wondering maybe there are some other ways that I haven't explored?





Is there a way to get Kotlin function's owner via reflection

Suppose we have the following functions:

class MyClass {
fun myFunction() {}
companion object {
    fun myStaticFunction() {}
}
}

fun myTopLevelFunction() {}

When I am debugging thru the following:

           val functions = listOf(
            MyClass::myFunction,
            MyClass.Companion::myStaticFunction,
            ::myTopLevelFunction
        )
        functions.forEach {
            val names = (it::class.java).fields.map {
                method -> println(method.name)
            }

Intellij can correctly show me in "Evaluate Expression" this information

  • owner (MyClass, MyClass.Companion etc.
  • whether this is a top level function

But I cannot find a way to do it via reflection. For instance, I cannot figure out how to read function's owner. What am I missing? TIA.

In Intellij I can see functions' owners like this

myFunction -> MyClass
myStaticFunction -> MyClass.Companion
myTopLevelFunction -> MyFileNameKt




jeudi 6 janvier 2022

Reflection, set.GetValue(context, null) always return null

I'm trying to get a property from an object by reflection.

public class CosmosDbSet<TEntity> : DbSet<TEntity> where TEntity : class, IEntity<string>
{
    public string Name { get; }
    //...
        );

}

public class SKCosmosDbContext : CosmosDBContext
{
    public CosmosDbSet<Item> Items { get; }

   public SKCosmosDbContext ()
   {
        Items = new CosmosDbSet<Item>(
            this,
            "Items"
        );
   }
    //...
}

public abstract class CosmosDBContext : DbContext
{
    public async Task EnsureContainersExistAsync()
    {
            var sets = GetType().GetProperties()
                .Where(pi => pi.PropertyType.IsGenericType
                    && pi.PropertyType.GetGenericTypeDefinition().Equals(typeof(CosmosDbSet<>))
                );
            foreach (var set in sets)
            {
                var value = set.GetValue(this, null); // => value is always null
                //...
            }
    }
}

public static class DbInitializer
{
    public async static Task InitializeAsync(IServiceProvider services, ILogger logger)
    {
        var dbContext = services.GetRequiredService<SKCosmosDbContext>();
        await dbContext.EnsureContainersExistAsync();
    }
}

As you can see, the property Items from SKCosmosDbContext has been found but, I can't have access to it. Description

How to have access to the property using reflection?





Obtain an instance of a field by Interface type?

I have an interface:

public interface IThings<T> where T : class
{
    public void Play();
}

that populates a class instance with several fields that may be added on to as the project progresses (so no switch statements).

I am attempting to call the Play interface method of a field based on it's interface type, but I do not have access to any particular field.

public class MyClass
{
    public IThings<Widget> Widgets;
    public IThings<Fidget> Fidgets;
    public IThings<Gizmo> Gizmos;
    public IThings<DooDad> DooDads;

    ...

    public void DoWork<T>() where T : IThings<class>
    {
            T.Play(); //does not compile, of course.
    }
}

I have tried dabbling in reflection –which I am not too proficient in– but I'm not sure how to get the instance. I'd also like to avoid relying on convention of field names to class names. I'm sure that would be easier, but it would be a potential source for bugs.

var fieldName = typeof(MyClass).GetRuntimeFields()
    .Where(t => t.FieldType == typeof(IThings<T>))
    .FirstOrDefault().Name;

The above code does actually get the name of the field I'm looking for. I just need to be able to call the method on that field.





mercredi 5 janvier 2022

empty interface'kind in go is invalid kind? [duplicate]

I want know the kind of empty interface,and test code is below,from the source code of go I find that there is a kind called Interface,but the output shows that interface{}'kind is invalid.

Why the interface{}'s kind is invalid and how can I get a Interface kind?

func main() {
        var i interface{}
        fmt.Println("kind:", reflect.ValueOf(i).Kind())
}

output: kind: invalid





reflection: getting the proper prameterized return type (List) from a generic method

Good Day!

I am experimenting a little bit with reflections and I've come to the following problem:

In short, details below:

I have a method from an interface that also only inherits this method from another interface and the return type is List<RS> (RS extends AbstractResponseObject). How do I get the methods return type for example List instead of List<RS> in a way similar to

ParameterizedType genericReturnType = (ParameterizedType) method.getGenericReturnType();

I have a main interface describing a rest interface running on my backend, similar to this:

public interface EntityRestController<RS extends AbstractResponseObject> {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    List<RS> findAll();

    ...
}

And for each entity, I have an interface just like this:

@RequestMapping("rest/customer")
public interface ICustomerRestController extends EntityRestController<ResponseCustomer> {

}

the latter one is empty and should only have methods for queries specific to the entity. but in any case it declares the endpoint for its entity.

now for all my entity interfaces I create a proxy using

E proxyInstance = (E) Proxy.newProxyInstance(
                    restInterface.getClassLoader(),
                    new Class[]{restInterface},
                    (proxy, method, args) -> handleInvoke(restInterface, method, args));

once a method is called handleInvoke is called and I check for @RequestMapping and its value for the path as well as its method and use these information creating the rest call using WebClient.

now I wonder how do I get the proper return type of my findAll() method returning a List? I have created the following code as an example:

        Class<?> returnType = method.getReturnType();
        ParameterizedType genericReturnType = (ParameterizedType) method.getGenericReturnType();
        WebClient.ResponseSpec responseSpec = webClient.get().uri(path).retrieve();
        Mono<?> mono = responseSpec.bodyToMono(ParameterizedTypeReference.forType(genericReturnType));
        Object o = mono.block(Duration.ofSeconds(30));
        return o;

using only returnType in responseSpec.bodyToMono would give me a List containing a HashMap with all the Customer information. Obviously I expect a List<ResponseCustomer> as a result. Using genericReturnType in responseSpec.bodyToMono, as shown in my example, throws an exception:

InvalidDefinitionException: Cannot construct instance of x.x.x.AbstractResponseObject (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information

which makes sense because the actual method is in the rather generic EntityRestController interface and returns RS which extends AbstractResponseObject. But how would I get the actual ResponseCustomer type?

any help is very appreciated.

cheers!





mardi 4 janvier 2022

MonoCecil giving the wrong method name when reading an F# binary by reflection

I have a net 6 F# binary that contains some methods, on which some have one or many [<TestCategory(CategoryName)>] attribute defined on them. My goal is to use reflection, from a C# application, to read and gather the fully qualified names of those test methods.

In order to achieve this, I am trying to use the Mono.Cecil library in order to read the information from the F# binary. This seems to work pretty well with C# binaries, but not so much with F# ones. The problem I am encountering is that the fully qualified name (and name) properties of the method Mono.Cecil gives me is under the format "BinaryName.ModuleName.f@LineNumber", instead of giving me "BinaryName.ModuleName.ActualMethodName".

Here is how I get the information via reflection using Mono.Cecil.

    private static IEnumerable<GenericModule> ReadModulesRecursively(string assemblyPath)
    {
        var modules = new List<GenericModule>();

        var assemblyDefinition = AssemblyDefinition.ReadAssembly(assemblyPath);
        foreach (var module in assemblyDefinition.Modules)
        {
            var moduleTypes = module.Types.Select(ToGenericType); // Construct a DTO containing only what I want
            modules.Add(new GenericModule(module.Name, moduleTypes));
        }

        return modules;
    }

    private static GenericType ToGenericType(TypeDefinition typeDefinition)
    {
        return new GenericType(typeDefinition.Name, typeDefinition.CustomAttributes.Select(ToGenericAttribute), typeDefinition.Methods.Select(ToGenericMethod));
    }

    private static GenericMethod ToGenericMethod(MethodDefinition methodDefinition)
    {
        return new GenericMethod(methodDefinition.Name, $"{methodDefinition.DeclaringType.FullName}.{methodDefinition.Name}", methodDefinition.DeclaringType.FullName,
            methodDefinition.CustomAttributes.Select(ToGenericAttribute));
    }

And here is an example of a F# method declaration I am trying to get information on, in the F# binary:

module myModule

<open statements...>

[<TestClass>]
[<DeploymentItem("Deploy1")>]
[<DeploymentItem("Deploy2")>]
type Tests ()=

    [<TestMethod>]
    [<TestCategory("Cat1")>]
    [<TestCategory("Cat2")>]
    member x.``This is a test title`` () =
        ()

So the problem here seems to be that the MonoCecil MethodDefinition type doesn't contain the right Name and FullName property values.

Is this a known issue with MonoCecil and F#, or am I doing something wrong?





How to call a parametriezed method having implicit argument using reflection in Scala?

Suppose there is a typical type class

trait Gen[T] {
  def generate(): T
}

object Gen {
  val random = new Random()

  implicit val stringGen: Gen[String] = () => random.nextString(10)
  implicit val intGen: Gen[Int] = () => random.nextInt()

  implicit def optionGen[T: Gen]: Gen[Option[T]] = () => Some(implicitly[Gen[T]].generate())
}

object Generator {
  def apply[T: Gen]: T = implicitly[Gen[T]].generate()
}

Calling Generator[Option[String]] will generate a random string wrapped in a Some.

How can Generator.apply be called at runtime via reflection having for example as parameter a type like val typeTag = typeOf[Option[String]]?





Class?> .isAnnotationPresent returns false for annotated class

I have my own annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Component {
}

And class:

package com.ltp.analog.test;

import com.ltp.analog.core.annotation.Component;

@Component
public class TestOne {

    public void test(){
        System.out.println("TEST ONE");
    }

}

Also implemented custom ClassLoader:


package com.ltp.analog.reflection;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class AnalogClassLoader extends ClassLoader{

    @Override
    public Class findClass(String name) {
        Class cl = findLoadedClass(name);

        if(cl != null){
            return cl;
        }

        byte[] b = loadClassFromFile(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassFromFile(String fileName)  {
        InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(
                fileName.replaceAll("[.]", "/") + ".class");
        byte[] buffer;
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int nextValue = 0;
        try {
            while ( (nextValue = inputStream.read()) != -1 ) {
                byteStream.write(nextValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        buffer = byteStream.toByteArray();
        return buffer;
    }

}

And ReflectionUtils class which have to load all the classes in package recursively:

package com.ltp.analog.reflection;

import com.ltp.analog.Testing;
import com.ltp.analog.reflection.qualifier.ClassQualifier;

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class ReflectionUtils {

    private static final AnalogClassLoader cl = new AnalogClassLoader();

    public static List<Class> getClassesInPackageRecursively(String packName){
        List<String> packs = getSubpackagesRecursively(packName);

        List<Class> result = new LinkedList<>();

        packs.forEach(pack -> result.addAll(getClassesInPackage(pack)));

        return result.stream().distinct().collect(Collectors.toList());
    }

    public static List<Class> getClassesInPackage(String packName){
        if(packName == null || packName.isEmpty()){
            return List.of();
        }

        URL url = ClassLoader.getSystemClassLoader().getResource(packName.replaceAll("[.]", "/"));

        if(url == null){
            return List.of();
        }

        File pack = new File(url.getPath());

        if(!pack.isDirectory() || pack.listFiles() == null){
            return List.of();
        }

        return Arrays.stream(pack.listFiles())
                .filter(File::isFile)
                .filter(f -> f.getName().endsWith(".class"))
                .map(f -> cl.findClass(packName + "." + f.getName().substring(0, f.getName().indexOf('.'))))
                .collect(Collectors.toList());
    }

    public static List<String> getSubpackagesRecursively(String packName){
        List<String> result = new LinkedList<>();

        for(String pack : getSubpackages(packName)){
            List<String> subPacks = getSubpackagesRecursively(pack);
            result.addAll(subPacks);
        }

        result.add(packName);

        return result.stream().distinct().collect(Collectors.toList());
    }

    public static List<String> getSubpackages(String packName){
        if(packName == null || packName.isEmpty()){
            return List.of();
        }

        URL url = ClassLoader.getSystemClassLoader().getResource(packName.replaceAll("[.]", "/"));

        if(url == null){
            return List.of();
        }

        File pack = new File(url.getPath());

        if(!pack.isDirectory() || pack.listFiles() == null){
            return List.of();
        }

        return Arrays.stream(pack.listFiles())
                .filter(File::isDirectory)
                .map(f -> packName + "." + f.getName())
                .collect(Collectors.toList());
    }

    private ReflectionUtils(){}

}

The problem is that after loading all the classes in the passed package I'm trying to filter them and get only annotated by @Component, but the result is weird:

someClass.isAnnotationPresent(Component.class) returns false, even when there is a @Component annotation in someClass.getDeclaredAnnotations()

Sample:

List<Class> componentClasses = new LinkedList<>();
        scans.forEach(s -> componentClasses.addAll(ReflectionUtils.getClassesInPackageRecursively(s)));
        System.out.printf("Classes: %d", componentClasses.size());
        componentClasses.forEach(c -> {
            System.out.println("-".repeat(50));
            System.out.println(Arrays.stream(c.getAnnotations()).map(Annotation::toString).collect(Collectors.joining(", ")));
            System.out.printf("%s -> %s\n", c.getName(), c.isAnnotationPresent(Component.class));
        });

The output:

...
@com.ltp.analog.core.annotation.Component()
com.ltp.analog.test.TestOne -> false
...




Unchecked cast: 'java.lang.reflect.Type' to 'java.lang.Class

my code:

public abstract class BaseMongoServiceImpl<E> implements BaseMongoService<E> {
    private final Class<E> entityClass;

    protected BaseMongoServiceImpl() {
        ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) parameterizedType.getActualTypeArguments()[0];
    }
}

(Class<E>) parameterizedType.getActualTypeArguments()[0]; warning: Unchecked cast: 'java.lang.reflect.Type' to 'java.lang.Class'

What should I do to remove this warning without annotation?

PLZ help me!





lundi 3 janvier 2022

Call Generic Class Constructor on runtime [duplicate]

I am having issues creating generic class instance. This is my code, please take a look at the remark. This is where the error ocurs. I want to put different types into a list and create instances according to the types that the user defined in the application. How can I achieve that ? I know how to use reflection with Activator but I don't know how can I create the generic class at runtime.

public class Field<T> : IField
{
   public string Name { get; set; }
   public Type Type => typeof(T)
}

IEnumerable<Type> types = new List<Type>{typeof(int),typeof(string)}

foreach(var type in types)
{
   var instance = new Field<type>() //error
}





Get property value of a complex type with reflection in c#

I have an object like this

oldEntity
     Active: true
    ActiveDirectoryName: ""
    ArchiveConceptValueList: null
    AsgScndCnpRangeDictionary: Count = 0
    AssignedRuleList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedRule>}
    AssignedScndCnpRangeList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedScndCnpRange>}
    AssignedScndCnpRangePeresentList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedScndCnpRange>}
    AssignedWGDShiftList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.AssignedWGDShift>}
    AssignedWorkGroupList: {GTS.Clock.Model.PersonWorkGroup, GTS.Clock.Model.PersonWorkGroup}
    Assistant: null
    BarCode: "0451343786"
    BasicTrafficController: {GTS.Clock.Model.Concepts.BasicTrafficController}
    BasicTrafficList: {}
    BudgetList: null
    CFPNeedUpdate: false
    CalcDateZone: null
    CardNum: "2465"
    CartOrgan: {GTS.Clock.Model.Charts.Department}
    CheckEnterAndExitInRequest: false
    CostCenter: {GTS.Clock.Model.BaseInformation.CostCenter}
    CurrentActiveContract: null
    CurrentActiveDateRangeGroup: null
    CurrentActiveRuleGroup: null
    CurrentActiveWorkGroup: null
    CurrentRangeAssignment: null
    CurrentYearBudgetList: {NHibernate.Collection.Generic.PersistentGenericBag<GTS.Clock.Model.Concepts.CurrentYearBudget>}
    DelayCartableList: {}
    Department: {GTS.Clock.Model.Charts.Department}
    DepartmentID: 0
    ...

And I want the name fiel of Department. Besides Department in oldEntity like this: enter image description here and properies of Department field like this: enter image description here

once I use below code to get name field of Department with Reflection ,I got this erro

oldEntity.GetType().GetProperty("Department").GetValue("Name", null);

Object does not match target type.





samedi 1 janvier 2022

How to detect the length of array property using reflection only if it actually is an array?

I'm converting an object based on reflection like this.

obj.GetType().GetProperties()

It produces the expected list of properties.

{System.Reflection.PropertyInfo[4]}
[0]: {System.String Name}
[1]: {System.Guid[] Ids}
[2]: {System.String[] Tags}
[3]: {System.Nullable`1[System.Boolean] Status}

Then, I want to clear the list of properties not in use, so I add the condition that a value of a property needs to differ from null.

obj.GetType().GetProperties()
  .Where(a => a.GetValue(obj) != null)

It produces the expected result for atomary fields but not the arrays (as they're undefinably not null, only empty).

{System.Linq.Enumerable.WhereArrayIterator<System.Reflection.PropertyInfo>}
[0]: {System.String Name}
[1]: {System.Guid[] Ids}
[2]: {System.String[] Tags}

I'm not sure how I should go about detecting non-null but empty array properties in order to exclude those. I can't simply cast to an array (as discussed here) because not every property is an array.

The closest approach I have is this piece of "work", which seems to be rather... undesired. It's got this distinct code smell going on.

obj.GetType().GetProperties()
  .Where(a => a.GetValue(obj) != null 
    && !(a.GetValue(obj) is Array && (a.GetValue(obj) as Array).Length == 0))

And as I try to create something with it using Select(a=>a.GetValue(obj)) it gets even clunkier and more obviously in desperate need of improvement. I also noticed that whenever the array isn't empty, my mapping fails producing System.String%5b%5d, which will probably require me to additionally clunkify the code.