vendredi 30 décembre 2022

NoSuchMethodException is throwing when trying to access getActivePasswordQuality() method of LockPatternUtils class

I want to get access to com.android.internal.widget.LockPatternUtils class object using reflection and want to know the Lock method user has set in Android device.

I am using below code for that :

    private fun getAuthenticationMethodType() : Int {
    var lockType = 0
    try {
        val lockPatternUtilsClass = Class.forName("com.android.internal.widget.LockPatternUtils")
        val lockPatternUtils =
            lockPatternUtilsClass.getConstructor(Context::class.java).newInstance(this)


        val method: Method = lockPatternUtilsClass.getMethod("getActivePasswordQuality")
        // === The above Line throws an exception NoSuchMethodException === //

        val method2: Method = lockPatternUtilsClass.getDeclaredMethod("getActivePasswordQuality",
                            Class.forName("android.os.UserHandle"))
       // === Tried above line too, but this Line also throws an exception NoSuchMethodException === //

        val userHandleClass = Class.forName("android.os.UserHandle")
        val myUserIdMethod = userHandleClass.getMethod("myUserId")
        val userId = myUserIdMethod.invoke(userHandleClass)

        lockType = method.invoke(lockPatternUtils, userId) as Int
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        Log.d("TAG","exception : " + e.printStackTrace())
    }
     return lockType
}

I know the above code works fine until Android 6. I am trying on Android 12.

I checked on Android Documentation Non-SDK API lists and found that getActivePasswordQuality and getKeyguardStoredPasswordQuality methods are marked as greyList. As per documentation of greyList, it says :

Unsupported (greylist) : Non-SDK interfaces that are currently unrestricted and your app can use. Note however, that these interfaces are unsupported and subject to change without notice. Expect these interfaces to be conditionally blocked in future Android versions in a max-target-x list.

But, these both methods are not accessible. My understanding is that the methods marked with greyList can be accessible. Is it correct?

Is there any mistake in my code?

How to know lock password type that user has set like PIN/Password/Pattern/Biometric, just categorisation is needed





mercredi 28 décembre 2022

How to find all sub classes of java.lang.Throwable in the JVM?

I want to find all sub classes of java.lang.Throwable in the JVM. The classes may or may not have been already loaded in the JVM.

I have read the similar question How do you find all subclasses of a given class in Java?, and I think org.reflections can solve my question.

I tried the following code:

public static void main(String[] args) {
    Reflections reflections = new Reflections( "org" ) ;
    Set<Class<? extends Throwable>> set = reflections.getSubTypesOf( Throwable.class ) ;
    for (Class<? extends Throwable> t : set) {
        System.out.println( t ) ;
    }
}

But the result is not what I expected:

class java.lang.Exception
class java.lang.RuntimeException
class org.reflections.ReflectionsException

I have two doubts:

  1. Why are java.lang.Exception and java.lang.RuntimeException in the result? I used the prefix "org".
  2. Why is java.lang.NullPointerException not in the result? It is in the package "java.lang" too.




Why does Assembly.GetType not get the type that exists in the target Assembly?

Assembly UnityEditorAssembly = Assembly.Load("UnityEditor");
Type[] allType = UnityEditorAssembly.GetTypes();
for (int i = 0; i < allType.Length; i++)
{
    if (allType[i].Name== "SceneAsset")
    Debug.LogError(allType[i].Name);
}
Type targetType = UnityEditorAssembly.GetType("SceneAsset",false,false);
Debug.LogError(targetType);

When I tried to get the SceneAsset type in UnityEditor by reflection, I could not get the target by Assembly.GetType, but by traversing to prove that the type existed at runtime. I wondered why





lundi 26 décembre 2022

Can I invoke a Kotlin coroutine from Java reflectively and wrap it in CompletableFuture?

I'm reflectively accessing a Kotlin class and trying to invoke a coroutine, wrapping it in a CompletableFuture. Looking at an example from Spring, they manage to wrap such a reflective call in a Mono using kotlinx-coroutines-reactor:

Mono<Object> mono = MonoKt.mono(Dispatchers.getUnconfined(), (scope, continuation) ->
                        KCallables.callSuspend(function, getSuspendedFunctionArgs(target, args), continuation));

I could easily just call Mono#toFuture() but I'm trying to avoid dragging in a dependency to Reactor. Can I achieve the same without going through Mono?

Looking at kotlinx-coroutines-jdk8, there seems to exist something similar to the above, but I can't figure out how to use it. Perhaps:

CompletableFuture<Object> future = FutureKt.future(
         GlobalScope.INSTANCE, Dispatchers.getUnconfined(), CoroutineStart.DEFAULT, (scope, continuation) ->
                KCallables.callSuspend(function, getSuspendedFunctionArgs(target, args), continuation));

But this is just a blind guess, as I have next to 0 Kotlin knowledge. Are CoroutineStart.DEFAULT or GlobalScope.INSTANCE even ok here?

Btw, how is Spring getting away with passing a CoroutineDispatcher (Dispatchers.getUnconfined()) where a CoroutineContext is expected?





What draws the line between reflective programming & non-reflective programming like simple softcoding?

Not sure if this is the right place to bring up this kind of discussion but, Im reading https://en.wikipedia.org/wiki/Reflective_programming and feel I need a bit further clarification for where the line between "reflective" & non-reflective programming really goes. Theres a series of examples of reflective v non-reflective code towards the end of the wikipedia page where all the "reflective" examples seem to access data with string identifiers - but what would actually differentiate this from say putting a bunch of objects in a collection/array of some sort and accessing them by an index - say compared to accessing them by an array of string identifiers that you can use to fetch the desired object?

In some languages you can clearly see the difference & benefit, like in Python & JS they have the eval method that lets them insert all sorts of code at runtime that can be pretty much endlessly complex and completely change the code flow of an application - and no longer limited to accessing mere special type objects. But in the examples listed on the wiki page you can also find examples where the "reflection" seems limited only to accessing specially declared objects by there name (at which point Im questioning if you can really argue that the program really can be considered to be "modifying" itself at all, at least on a high level in conceptual point of view).

Does the way that the underlying machinery producd by the compiler (or the way that the interpreter reads your code) affect whats considered to be reflective?

Is the ability of redefining the contents of existing objects or declaring new objects without a "base class"/preexisting structure created at compile time that differentiates reflective & non-reflective code? If so, how would this play with the examples at the wikipedia page that doesnt seem to showcase this ability?

Can the meaning of "reflective programming" vary slightly depending on the scenario?

Any thoughts appreciated <3





.NET Reflection: Type is resolved from Assembly, but not from Module

I have the following code which loads an assembly via LoadFile and tries to get a generic type from it (.NET 6):

using System.Reflection;

var assemblyPath = "D:\\jb_lifetimes\\JetBrains.Lifetimes.dll";
var typeName = "JetBrains.Util.Util.StaticsForType`1[[JetBrains.Threading.ByteBufferAsyncProcessor," +
               " JetBrains.Lifetimes, Version=777.0.0.0, Culture=neutral, PublicKeyToken=3c74c1a6a8683340]]";
var moduleName = "D:\\jb_lifetimes\\JetBrains.Lifetimes.dll";

var assembly = Assembly.LoadFile(assemblyPath);
var fromAssembly = assembly.GetType(typeName);

Console.WriteLine($"Module count: {assembly.Modules.Count()}");

var module = assembly.GetModules().First(m => m.FullyQualifiedName == moduleName);
Console.WriteLine($"Resolved module: {module}");

Console.WriteLine($"Types count in module: {module.GetTypes().Length}");
Console.WriteLine($"Types count in assembly: {assembly.GetTypes().Length}");

var fromModule = module.GetType(typeName);

Console.WriteLine($"From assembly: {fromAssembly}");
Console.WriteLine($"From module: {fromModule}");

And get the following output:

Module count: 1
Resolved module: JetBrains.Lifetimes.dll
Types count in module: 316
Types count in assembly: 316
From assembly: JetBrains.Util.Util.StaticsForType`1[JetBrains.Threading.ByteBufferAsyncProcessor]
From module:

Type is resolved when it is acquired from Assembly.GetType, but Module.GetType returns null, however there is only one module in this assembly, and it is successfully resolved.

I don't understand why the type cannot be resolved from the only module of the assembly when it is successfully resolved from the assembly itself.

Some other observations:

  • If I replace LoadFile with LoadFrom, type is resolved from module as well. I know about different load contexts, but can't understand how they can affect the observed behavior
  • If I replace type name with JetBrains.Util.Util.StaticsForType1[JetBrains.Threading.ByteBufferAsyncProcessor], it is also resolved from module even with LoadFile




vendredi 23 décembre 2022

CreateDelegate: "ArgumentException: Cannot bind to the target method because its signature is not compatible with that of the delegate type."

I am writing a GUI program using AvaloniaUI. The part I'm stuck on right now is that I'm trying to add some code to the ViewModel's constructor that binds some methods to events defined in the VM using Reflection. This is what I have right now:

namespace Program
{
    [AttributeUsage(AttributeTargets.Method)]
    [MeansImplicitUse]
    internal sealed class AttachToEventInViewModelAttribute : Attribute
    {
        internal string EventName;

        public AttachToEventInViewModelAttribute(string EventName) =>
            this.EventName = EventName;
    }
}

namespace Program.Models
{
    public static class ExtractFiles
    {
        [AttachToEventInViewModel("onStartExtraction")]
        internal static void Extract()
        {
        }
    }
}

namespace Program.Views
{
    public partial class MainWindow : Window
    {
        private readonly Window instance;

        public MainWindow()
        {
            instance = this;
            InitializeComponent();
        }

        [AttachToEventInViewModel("onGetWindow")]
        public Window GetInstance() =>
            instance;
    }
}

namespace Program.ViewModels
{
    public sealed class MainWindowViewModel : ViewModelBase
    {
        // ==== Constructor ====
        public MainWindowViewModel()
        {
            <snip code for finding the GetInstance() and Extract() methods, which is working>
            
            MethodInfo method = allMethodsInType[j];
            object[] allAttributesOnMethod = method.GetCustomAttributes(typeof(AttachToEventInViewModelAttribute), false);

            AttachToEventInViewModelAttribute methodAttribute = (AttachToEventInViewModelAttribute) allAttributesOnMethod[0];
            BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic;

            EventInfo? methodEventInfo = this.GetType().GetEvent(methodAttribute.EventName, bindingFlags);
            if (methodEventInfo == null)
                continue;

            Type? methodEventType = methodEventInfo.EventHandlerType;
            if (methodEventType == null)
                continue;

            Delegate methodEventHandler = Delegate.CreateDelegate(methodEventType, this, method);
            methodEventInfo.AddEventHandler(this, methodEventHandler);
        }


        // ==== Events ====
        private event Action onStartExtraction;

        private event Func<Window> onGetWindow;
    }
}

However, when I try run this code, the CreateDelegate method triggers the Exception in the title. The strange part is that if I add the following lines to the MainWindowViewModel constructor, the compiler has no problem with them, implying that the signatures are actually compatible:

            onGetWindow += new MainWindow().GetInstance;
            onStartExtraction += ExtractFilesFromBsaRecords.Extract;

I searched the site and found other questions with this problem, but none of them helped. For the most part, the problem in those was that the asker used the CreateDelegate overload for static events.





Golang reflect/iterate through interface{}

I’m looking to iterate through an interfaces keys.

Goal:

  • I want to implement a kind of middleware that checks for outgoing data (being marshalled to JSON) and edits nil slices to empty slices.
  • It should be agnostic/generic so that I don't need to specify field names. Ideally I can pass any struct as an interface and replace nil slices with empty slices.

Controller level

type Tag struct {
  Name string
}
type BaseModel struct {
  ID uuid.UUID
  Active bool
}
type Model struct {
  BaseModel // embedded struct
  Name string
  Number int
  Tags []Tag
}

newModel, err := GetModel()
if err != nil {
   ...
}

RespondAsJson(w, newModel)

Middleware / Middle man json responder

  • It takes an interface to be generic/agnostic and reusable in many different controllers
//(1) Attempting to use a map
func RespondWithJson(w http.ResponseWriter, data interface{}) {
   obj, ok := data.(map[string]interface{})
   // (1.1) OK == false

   obj, ok := data.(map[interface{}]interface{})
   // (1.2) OK == false

   var newMap map[string]interface{}
   bytes, _ := json.Marshal(&obj)
   json.unMarshal(bytes, &newMap)
   // (1.3) newMap has no underlying types on fields
   // Nil slice of Tags went in, and it comes out as
   // value=nil and type=interface{} 
}

//(2) Skipping two as I believe this works, I'd like to avoid implementing it though.
//(3) 
//(3.1) 

RespondWithJson(w, newModel)
func RespondWithJson(w http.ResponseWriter, data interface{}) {

   e := reflect.ValueOf(&data) // data = {*interface{} | Model}
   if e.Kind() == reflect.Pointer {
     e = e.Elem()
     // e has a flag of 22, e.Elem() has a flag of 404
   }
    for i := 0; i < e.NumField(); i++ {
//PANIC: reflect: call of reflect.Value.NumField on interface Value
    ...
    }
}
//(3.2) 
// Reference: https://go.dev/blog/laws-of-reflection (third law)

RespondWithJson(w, newModel)
func RespondWithJson(w http.ResponseWriter, data interface{}) {

   e := reflect.ValueOf(data) // data = {interface{} | Model}
   if e.Kind() == reflect.Pointer {
     e = e.Elem()
   }
    for i := 0; i < e.NumField(); i++ {
        field := e.Field(i)
        if field.Kind() == reflect.Slice && field.isNil() {
            ok := field.CanSet() // OK == false
         // Reference third law description in the reference above
            valueOfField1 := reflect.ValueOf(&field)
            ok := valueOfField1 .CanSet() // OK == false
            ...
            valueOfField2 := reflect.ValueOf(field.Interface())
            ok := valueOfField2.CanSet() // OK == false
            ...
        }
    }
}
//(3.3) 
// Reference: (https://stackoverflow.com/questions/64211864/setting-nil-pointers-address-with-reflections) and others like it
RespondWithJson(w, newModel)
func RespondWithJson(w http.ResponseWriter, data interface{}) {
  e := reflect.ValueOf(data) // {interface{} | Model}
  if e.Kind() == reflect.Pointer { e = e.Elem() }
  for i := 0; i < e.NumField(); i++ {
    field := e.Field(i)
    if field.Kind() == reflect.Slice && field.IsNil() {
      tmp := reflect.New(field.Type())
      if tmp.Kind() == reflect.Pointer { tmp = tmp.Elem()}

      // (3.3.1)
      ok := tmp.CanSet() // OK == true
      tmp.Set(reflect.MakeSlice(field.Type(),0,0))
      ok := field.CanSet()
      // OK == false, tmp.set doesn't affect field value && can't set 
      field with value of tmp
    
      // (3.3.2)
      ok := tmp.Elem().CanSet() 
      // PANIC - call of reflect.value.Elem on Slicevalue
      ...
    }

  }
}
//(3.4) 
// I can get it to work with passing &model to the function
// Once I'm inside the function, it's seen as an interface (or a
// *interface and the above is my results

RespondWithJson(w, &newModel)
func RespondWithJson(w http.ResponseWriter, data interface{}) {
   e := reflect.ValueOf(data) // Data is {interface{} | *Model}
   if e.Kind() == reflect.Pointer {
     e = e.Elem()
     // e has a flag of 22, e.Elem() has a flag of 409
   }
    for i := 0; i < e.NumField(); i++ {
        field := e.Field(i)
        if field.Kind() == reflect.Slice && field.IsNil() {
            ok := field.CanSet()
            // OK == true, field is addressable
            if ok {
                field.Set(reflect.MakeSlice(field.Type(), 0, 0))
                // Success! Tags: nil turned into Tags: []
            }
        }
    }
}

After that and many more.. random interations, I've found a way to make it work by passing memory address of struct to function which takes interface value.

If possible, I'd like to avoid the need to do this, as the function signature won't pick it up and it just leaves a small amount of room for error for other people on my team. I can of course just document the function, but its not bullet proof :)

Does anyone have suggestions for making this work without starting with a memory address to a struct? Can I set a field of an interface? ty very much!





Failed in Tensorflow Serving gRPC reflection

I'm trying to add a gRPC health check endpoint in tensorflow serving. I added these code into tensorflow_serving/model_servers/server.cc and re-compiled it:

::grpc::EnableDefaultHealthCheckService(true);
::grpc::reflection::InitProtoReflectionServerBuilderPlugin();

After that I run it and test with grpcurl: grpcurl -plaintext localhost:8500 list It shows:

grpc.health.v1.Health
grpc.reflection.v1alpha.ServerReflection 
tensorflow.ProfilerService 
tensorflow.serving.ModelService 
tensorflow.serving.PredictionService

But when I try grpcurl -plaintext localhost:8500 grpc.health.v1.Health/Check It says:

Error invoking method "grpc.health.v1.Health/Check": target server does not expose service "grpc.health.v1.Health"

It's quite a simple feature but have been stucking me for several days. Could someone help? Thanks in advance!





mercredi 21 décembre 2022

How do I identify class properties that are public with an enum return type?

I have automatically generated service references and I need to analyze them to identify classes with public properties that return enums. This is for an asp.net project that was originally serializing enums as int and was converted to string, so I'm trying to produce a list of enums and their int/string values.

I just copied & pasted all of the service references into a .NET console project and I'm able to enumerate the properties and I am focusing on a known enum for testing, but the output from the below code is not identifying it as an enum when it is:

[AxdEntity_PurchTable_1\Property\PurchStatus]: Nullable`1; False

How can I correctly identify it as an enum?

My Reflection Code:

var q = from t in Assembly.GetExecutingAssembly().GetTypes()
            where t.IsClass && t.Namespace == "MyNamespace"
            && t.Name == "AxdEntity_PurchTable_1" // I plan to remove this, but focusing on one class
            select t;

foreach (var refClass in q.ToList())
{
    foreach (var prop in refClass.GetProperties())
    {
        if (prop.Name == "PurchStatus")
        {
            // How do I determine if the return type is an enum?
            Console.WriteLine($"[{refClass.Name}\\Property\\{prop.Name}]: {prop.PropertyType.Name}; {prop.PropertyType.BaseType.IsEnum}");

            // OUTPUT: [AxdEntity_PurchTable_1\Property\PurchStatus]: Nullable`1; False

            // prop.PropertyType.BaseType.IsEnum == false?
        }
    }
}

Automatically generated service reference sample code:

namespace MyNamespace
{
    // <... Many other generated classes in this namespace>
    public partial class AxdEntity_PurchTable_1
    {
        private System.Nullable<AxdEnum_PurchStatus> purchStatusField;
        
        // <... Many other properties in this class ...>
        public System.Nullable<AxdEnum_PurchStatus> PurchStatus
        {
            get
            {
                return this.purchStatusField;
            }
            set
            {
                this.purchStatusField = value;
            }
        }
    }
    
    // <... Many other enums in this namespace ...>
    public enum AxdEnum_PurchStatus
    {
        None,
        Backorder,
        Received,
        Invoiced,
        Canceled,
    }
}




Get marked variable name as default value for propertyWrapper

Lets say I have a property Wrapper to fetch Feature Flag from a service and assign to a Boolean if it is enabled of not

@propertyWrapper final class FeatureToggle {
    
    var clientContainer: ConfigurableFeatureFlagClient
    private let key: String
    
    var wrappedValue: Bool {
       FeatureFlag(clientContainer: clientContainer).isEnabled(key: key)
     }

    init(key: String, container: ConfigurableRemoteConfigClient = RemoteConfigClient.shared) {
        self.clientContainer = container
        self.key = key
    }
}

// Test Class
class TestFeatureToggle {

  @FeatureToggle(key: "isFeatureEnabled")
  var isFeatureEnabled 
}

I'm trying to Make this FeatureToggle Property Wrapper to assume that key default value will be the variable name marked with the property Wrapper, so if @FeatureToggle is marking var isFeatureEnabled so the key will automatically be isFeatureEnabled

Currently I tried using the #function as default value to get the class and use Mirror reflection to get the variable name of the class marked with the property Wrapper

@propertyWrapper final class FeatureToggle {

var clientContainer: ConfigurableRemoteConfigClient
private let key: String

var wrappedValue: Bool {
    let factoryClass = Bundle.main.classNamed(key) as! NSObject.Type // Force Unwrap just to simplify the example
    let factory = factoryClass.init()
    let mirror = Mirror(reflecting: factory)
    for child in mirror.children {
        guard let featureToggle = child.value as? FeatureToggle else { continue }
        let formattedValue = child.label?.dropFirst() // Drop the _ inserted by OBJC
        return FeatureFlag(clientContainer: clientContainer).isEnabled(key: formattedValue)
    }
    return false
}

init(key: String = #function, container: ConfigurableRemoteConfigClient = RemoteConfigClient.shared) {
    self.clientContainer = container
    self.key = key
    print("Self.key == \(self.key)") // It will print "TestFeatureToggle" using my class in previous code
} }

It works but i have to make the class TestFeatureToggle with @objc and makes it inherit from NSObject. Not to mention that this solution looks kind of ugly and hacky. My question is, is there an easier way without exposing to OBJC runtime or a more clean solution?





dimanche 18 décembre 2022

c# How to get a value from a method using reflection

Hi how can I execute all methods in a class and get the value from that call I'm stuck at ?????

(I'm using .net 4.8)

I would like to exetute all methods when the program starts, to make sure all config values are in the config file So I dont have ConfigurationManager.AppSettings all over the code but all config values are located in a specific class

public static void CheckConfigValues()
{
    var cv = new ConfigValues();
    var cvt = cv.GetType();
    var cvm = cvt.GetMethods();

    foreach (var item in cvm)
    {
        var itemValue = ?????
        if(string.IsNullOrEmpty(itemValue))
        {
            throw ...
        }
    }
}       
public class ConfigValues
{
    public static int GetMaxCalendarItems()
    {
          return int.Parse(ReadKeyFromAppConfig("GetMaxCalendarItems"));
    }
    
    public static int GetSomething....()
    {
          return int.Parse(ReadKeyFromAppConfig("Something"));
    }
    
    public static string ReadKeyFromAppConfig(string keyName)
    {
        try
        {
            var keyValue = ConfigurationManager.AppSettings[keyName];
            if (!string.IsNullOrEmpty(keyValue))
            {
                return keyValue;
            }
            else
            {
                Logger.Error($"Unable to read variable {keyName});
                throw new MissingFieldException(keyName);
            }   
            




samedi 17 décembre 2022

Using Reflection to Iterate and update value of an object for specific property types

I have an object, employeesOfTheMonth of type EmployeesOfTheMonth, which contains a number of properties of types Employee as well as List<Employee>. In some instances, the value of a given employee's JobTitleUpdated field contains an updated job title; in other instances, the JobTitleUpdated field is null.

    public class Employee
    {
        public int EmployeeId {get; set; }
        public string EmployeeName { get; set;}
        public string? JobTitle { get; set; }
        public string? JobTitleUpdated { get; set;}
        public decimal Salary { get; set; }
        public byte[] Photo { get; set; }
    }

    public class EmployeesOfTheMonth
    {   
        public string Company
        public Employee EmployeeOfTheMonthLocation1 {get; set;}
        public Employee EmployeeOfTheMonthLocation2 {get ;set;}
        public Employee EmployeeOfTheMonthLocation3 {get; set;}
        public List<Employee> EmployeesOfPriorMonthsLocation1 {get; set;}
        public List<Employee> EmployeesOfPriorMonthsLocation2 {get; set;}
        public List<Employee> EmployeesOfPriorMonthsLocation3 {get; set;}
        public DateTime ModifiedDate { get; set; }
        [... additional properties of various types snipped...]
    }

Using Reflection, I would like to iterate the properties of employeesOfTheMonth. If the property is of type Employee and if the JobTitleUpdated property of a given Employee contains data, I need to update the value of the JobTitle of the Employee with the value of the JobTitleUpdated property. In the case of List<Employee>, I need to iterate through that list and apply the same logic, namely conditionally updating the JobTitle with the JobTitleUpdated property.

Can this be done via Reflection?





Get the count of Model Required properties that filled

In my ASP.NET MVC application, I have created a model for customer details to be saved in the database.

When I retrieved the data from the database in the controller, I want to get out of the required field how many fields were filled.

How to get this done on the controller?

This is done for an existing database, I'm building a new project based on that database.

So when retrieving the data from the database and passing the data to the view, I want to pass that out of the required fields, and this count is filled.

I can assign the required fields to count to a property.

Other count is needed to know how to get it.

This is an example model


[Key]
public int Id { get; set; } 

[Required]
[DisplayName("Surname")]
public string Sur_Name { get; set; }

[Required]
[DisplayName("Name")]
public string Name { get; set; }

[Required]
[DisplayName("Citizenship")]
public int Citizen_Country_Id { get; set; }

I have tried this, want to know if the way is correct.

int countRequired = customer.GetType().GetProperties().Select(x=>x.GetValue(customer,null)).Count(c=>c ==null);





How to efficiently access private fields of object instead of Reflection

I have a use case where in I want to filter out results based on the input I receive from the user.

e.g.

Class Clazz 
   private field x;
   private field y;
   private field z;

In request I'll receive 2 values which field to filter on and what should be it's desired value

e.g.

request : 
   field      : x //
   fieldValue : "123"

So I used Reflection to find which field I need to be filtering on and applied lambda operation to get the desired result

    final Clazz obj = new Clazz(x: "123",y: "abc", z: "pqr");

    final Field requestedAttribute = randomMerchantDetails.getClass().getDeclaredField(request.getAttribute().toString());

    final String output = requestedAttribute.get(obj)

But since Reflection is not an efficient way of doing this and it should be avoided, is there any other way to do this?

Open to 3P libraries also

I tried using ReflectASM but I couldn't access the private fields.

Any efficient approach for solving this would be appreciated





jeudi 15 décembre 2022

Why do I see different methods with reflection vs browsing the source code?

My goal is to create strings from char arrays in Java. The String class has a constructor that accepts a char array and creates a new String object, this works well. However, this constructor makes a defensive copy of the char array, which I am trying to avoid.

I was browsing the source code of the String class (for Java 8, 11 and 17), and I happened to come across a package-private constructor that does exactly what I need:

    /*
    * Package private constructor which shares value array for speed.
    * this constructor is always expected to be called with share==true.
    * a separate constructor is needed because we already have a public
    * String(char[]) constructor that makes a copy of the given char[].
    */
    String(char[] value, boolean share) {
        // assert share : "unshared not supported";
        this.value = value;
    }

Since the constructor is not public, I thought I might be able to use it with reflection. However, when I try to list all the declared constructors for the String class, I don't see the above constructor:

|  Welcome to JShell -- Version 11.0.16.1
|  For an introduction type: /help intro

jshell> import java.lang.reflect.Constructor

jshell> var ctors = String.class.getDeclaredConstructors()
ctors ==> Constructor[18] { public java.lang.String(byte[]) ... ng.String(int[],int,int) }

jshell> for (Constructor<?> c: ctors) System.out.println(c)
public java.lang.String(byte[])
public java.lang.String(byte[],int,int)
public java.lang.String(byte[],java.nio.charset.Charset)
public java.lang.String(byte[],java.lang.String) throws java.io.UnsupportedEncodingException
public java.lang.String(byte[],int,int,java.nio.charset.Charset)
java.lang.String(char[],int,int,java.lang.Void)
java.lang.String(java.lang.AbstractStringBuilder,java.lang.Void)
public java.lang.String(java.lang.StringBuilder)
public java.lang.String(java.lang.StringBuffer)
java.lang.String(byte[],byte)
public java.lang.String(char[],int,int)
public java.lang.String(char[])
public java.lang.String(java.lang.String)
public java.lang.String()
public java.lang.String(byte[],int,int,java.lang.String) throws java.io.UnsupportedEncodingException
public java.lang.String(byte[],int)
public java.lang.String(byte[],int,int,int)
public java.lang.String(int[],int,int)

In the above output, I also see some constructors that I don't see in the source code, for example java.lang.String(java.lang.AbstractStringBuilder,java.lang.Void). Can someone help me understand this behavior? Why is the list of constructors from reflection different from the ones in the source code?

I am not using any security manager, in case that influences the answer. Also using vanilla openjdk (tried on version 8, 11 and 17).





Kotlion: invoke same overridden function in all sealed subclasses that implements same interface

I'm trying to invoke same function that in the subclasses the implements same interface. Or the question could be how to invoke function in KClass<out Drink>? Is it possible or is there any work around?

fun main() {
    println(Tea().getOptimalTemp())
    println(Wine().getOptimalTemp())
    val list = listOf(Drink::class.sealedSubclasses)
    for(drink in list){
        println(drink.getMethods.getOptimalTemp())
    }
}

interface Drink {
    fun getOptimalTemp(): Int
}

class Tea : Drink {
    override fun getOptimalTemp():Int{
        return 60
    }
}

class Wine : Drink {
    override fun getOptimalTemp():Int{
        return 10
    }
}

I expect to add more class implements that interface in the future without changing the loop.





mardi 13 décembre 2022

I want to get all properties of a class, how to do it in Java

I am working in a Spring project and I need to access every property of a given POJO to receive it's name. Right now I am using Java reflection and it is working exactly how I expect it to behave, but I am not sure about it being a smart solution. Another problem using Reflection is that the properties are private so I would have to use field.setAccessibility(true) for every field, which I guess is not a elegant solution, even though only the Field instance is changed. Maybe someone can provide me more information about this use case.

Greetings

Used Java Reflection and it worked but I don't know if it's the best solution. Maybe someone can provide me more detailed information about this use case





Reflect API and Serialization via JSON.stringify

The following JavaScript code does something I didn't expect.

let foo = {};
Reflect.defineProperty(foo,'bar',{value:1});
console.log(foo); // { bar: 1 }
console.log(JSON.stringify(foo)); // { }

Why is the serialized output from JSON.stringify missing the new bar property?





Why doesn't .NET find an assembly?

I am developing a .NET application (using C#). It uses reflection, including class System.Reflection.Assembly.

I have a .dll assembly in a file (the path is known), and I want to load it into Assembly. I use this code:

using System.Reflection;

// ...

var assembly = Assembly.LoadFile("AssemblyPath");

But it just doesn't find the assembly, despite the fact that it exists. The exception was of type System.IO.FileNotFoundException, and here's its message:

Could not load file or assembly 'C:\Users\Вова\source\repos\StreamingTest\bin\Debug\net7.0-windows10.0.22621.0\AForge.Video.FFMPEG.dll'. The specified module was not found.

What I have tried

  1. I ran this line. It wrote True.
Console.WriteLine(File.Exists("AssemblyPath"));
  1. I tried using Assembly.Load instead of Assembly.LoadFile. Exception was the same.

  2. Didn't find any answers neither on Stack Overflow, nor in the Internet.





lundi 12 décembre 2022

How to get an enum of static class members in Java?

I have a Java class (which I do not control and cannot modify) which has a large number of static String members. How can I have these as an enum (for convenience in coding)?

E.g. I have:

public class ClassWithStaticMembers {
  public static String ONE = "one";
  public static String TWO = "dos";
}

...and I want to derive the following from it:

public enum NUMBERS {
  ONE,
  TWO
}

Is this possible, with reflection or otherwise?

(Assume I don't know Java well, and that I have 100+ values, so repeating each is painful and not desirable (in case more values get added later). Also I don't need the actual values from the class ("one" and "dos" above)).





How to read the assembly version using Reflection?

I've got a .dll from a NuGet package that I use in a Blazor WebAssembly application. I want to be able to read the version of it.

Currently I read the version like so:

FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(Path.Combine(contentRootPath, @"bin\debug\net6.0\AssemblyName.dll"));
var version = $"{fileVersionInfo.FileDescription} ({fileVersionInfo.FileVersion})";

Instead of writing a path like this bin\debug\net6.0\AssemblyName.dll how can I load the assembly and use Reflection to get the version?





dimanche 11 décembre 2022

Create an instance of an object via string, in VB.NET, .NET Core 6

I have a project with about 100+ custom user controls in VB.NET, using the newest .NET Core 6 framework. These controls are added to different Forms when the Form load.

I am trying to create an instance of a specific control by using a string (which stores the control name), and then access its properties. For example, if I have a control named Control1, the string would store "Control1".

I have tried using Reflection (see below, but I am getting returned "Nothing"). What am I doing wrong?

Dim sControlType as String 'example = "Control1", or "Control2", etc
Dim objControl as Object = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(sControlType) 'objControl returns Nothing??

Second, after creating an instance of the object, I wish to convert the "Object" to the actual Type. Is this how it is done?

objControl = Convert.ChangeType(objControl , Type.GetType(sControlType))

Lastly, after converting the "Object" to the actual Type, I then want to access methods and properties from this Type. Is the following how it is done?

Dim objControl_Type As Type = objControl.GetType
If objControl_Type.GetField("Dock") IsNot Nothing Then objControl.Dock = DockStyle.Fill

Thank you very much.





Java 8: Why a WrongMethodTypeException from MethodHandle? Is my object type incorrect?

I have encountered a problem while I am trying to switch my event system from reflection to MethodHandle.

I am using an event bus (version 3.0.0) by KyoriPowered on Github (https://github.com/KyoriPowered/event).

My code is following:

public class EventExecutorFactory implements EventExecutor.Factory<Event, Listener> {
    @Override
    public @NonNull EventExecutor<Event, Listener> create(@NonNull Object object, @NonNull Method method) throws Exception { // object is Listener
        method.setAccessible(true);
        Class<? extends Event> actualEventType = method.getParameterTypes()[0].asSubclass(Event.class);
        MethodHandle handle = MethodHandles.lookup().unreflect(method);
        return new EventExecutor<Event,Listener>() {

            @Override
            public void invoke(@NonNull Listener listener, @NonNull Event event) throws Throwable {
                if (!actualEventType.isInstance(event)) return; // many different event types defined in my system, so I should check it first.
                handle.invoke(actualEventType.cast(event)); // WrongMethodTypeException thrown here
            }
        }
    }
}

I expected everything works fine.

But the result is:

java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(,UserOnlineEvent) to (Event)void

UserOnlineEvent is the event type that used in test.

But the problem is that I cannot get the real type of the event.





jeudi 8 décembre 2022

Java/Android reflection: type casting of Intent's Extra

In a system with Android (minimum Sdk 26) there is a package with a class of this kind: `

public class Example implements Serializable {
`    `private String[] field1;
`    `private ArrayList<Integer> field2;

`    `public method1(String[] field1, ArrayList<Integer> field2) {
`        `this.field1 = field1;
`        `this.field2 = field2;
`    `}

`    `private String method2 {
`        `// Some method that returns a String
`    `}
}

`

My package receives an object (an instance of that class) through an intent 'i', sent in this way:

Intent i = new Intent();  
i.putExtra("key", obj);  
setResult(Activity.RESULT_OK, i);  
finish();  

I do not have the full java file of class Example. However, my package (different from the one that sends the intent. It is in a separate apk) contains a Class object 'cl' of class Example (obtained through reflection) and a method object 'met' (method2, obtained through reflection as well). I need to call such method on the received object and print the resulting String on the Logs. How can this be done?

I tried the following:

met.setAccessible(true);  
String s = (String) met.invoke(cl.cast(i.getSerializableExtra("key")), null);  
if (s != null){  
`    `Log.d("TAG", s);  
} else{  
`    `Log.e("TAG", "null");  
}  

But nothing is printed on the log. I also tried this:

met.setAccessible(true);  
String s = (String) met.invoke(cl.cast(i.getSerializableExtra("key")), (Object) null);  
if (s != null){  
`    `Log.d("TAG", s);  
} else{  
`    `Log.e("TAG", "null");  
}  

But the same happened. Moreover, I tried to invoke the method through:

cl.cast(i.getExtras())

Instead of the previous case, but I obtained a Class Cast Exception (which I think is because intent.getExtras() returns a Bundle)





mercredi 7 décembre 2022

How do I inspect function arguments at runtime in Rust?

Say I have a trait that looks like this:

use std::{error::Error, fmt::Debug};
use super::CheckResult;

/// A Checker is a component that is responsible for checking a
/// particular aspect of the node under investigation, be that metrics,
/// system information, API checks, load tests, etc.
#[async_trait::async_trait]
pub trait Checker: Debug + Sync + Send {
    type Input: Debug;

    /// This function is expected to take input, whatever that may be,
    /// and return a vec of check results.
    async fn check(&self, input: &Self::Input) -> anyhow::Result<Vec<CheckResult>>;
}

And say I have two implementations of this trait:

pub struct ApiData {
    some_response: String,
}

pub MetricsData {
    number_of_events: u64,
}

pub struct ApiChecker;

impl Checker for ApiChecker { 
    type Input = ApiData;

    // implement check function
}
 
pub struct MetricsChecker;

impl Checker for MetricsChecker { 
    type Input = MetricsData;

    // implement check function
}  

In my code I have a Vec of these Checkers that looks like this:

pub struct MyServer {
    checkers: Vec<Box<dyn Checker>>,
}

What I want to do is figure out, based on what Checkers are in this Vec, what data I need to fetch. For example, if it just contained an ApiChecker, I would only need to fetch the ApiData. If both ApiChecker and MetricsChecker were there, I'd need both ApiData and MetricsData. You can also imagine a third checker where Input = (ApiData, MetricsData). In that case I'd still just need to fetch ApiData and MetricsData once.

I imagine an approach where the Checker trait has an additional function on it that looks like this:

fn required_data(&self) -> HashSet<DataId>;

This could then return something like [DataId::Api, DataId::Metrics]. I would then run this for all Checkers in my vec and then I'd end up a complete list of data I need to get. I could then do some complicated set of checks like this:

let mut required_data = HashSet::new();
for checker in checkers {
    required_data.union(&mut checker.required_data());
}

let api_data: Option<ApiData> = None;
if required_data.contains(DataId::Api) {
    api_data = Some(get_api_data());
}

And so on for each of the data types.

I'd then pass them into the check calls like this:

api_checker.check(
    api_data.expect("There was some logic error and we didn't get the API data even though a Checker declared that it needed it")
);

The reasons I want to fetch the data outside of the Checkers is:

  1. To avoid fetching the same data multiple times.
  2. To support memoization between unrelated calls where the arguments are the same (this could be done inside some kind of Fetcher trait implementation for example).
  3. To support generic retry logic.

By now you can probably see that I've got two big problems:

  1. The declaration of what data a specific Checker needs is duplicated, once in the function signature and again from the required_data function. This naturally introduces bug potential. Ideally this information would only be declared once.
  2. Similarly, in the calling code, I have to trust that the data that the Checkers said they needed was actually accurate (the expect in the previous snippet). If it's not, and we didn't get data we needed, there will be problems.

I think both of these problems would be solved if the function signature, and specifically the Input associated type, was able to express this "required data" declaration on its own. Unfortunately I'm not sure how to do that. I see there is a nightly feature in any that implements Provider and Demand: https://doc.rust-lang.org/std/any/index.html#provider-and-demand. This sort of sounds like what I want, but I have to use stable Rust, plus I figure I must be missing something and there is an easier way to do this without going rogue with semi dynamic typing.

tl;dr: How can I inspect what types the arguments are for a function (keeping in mind that the input might be more complex than just one thing, such as a struct or tuple) at runtime from outside the trait implementer? Alternatively, is there a better way to design this code that would eliminate the need for this kind of reflection?





mardi 6 décembre 2022

C# record - Assign Multiple Properties using Reflection On Same Instance

Since record type is immutable, a new instance is created whenever a property is set

My question is: using reflection, is it possible to set values to multiple properties without creting new instance on every assignment (same as with reserved word)?

Thank you!

public class Program
{
    public record Person
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }
    }

    public static void Main()
    {
        var p = new Person();
        Console.WriteLine("Hashcode BEFORE property assignment: " + p.GetHashCode());
        var pis = p.GetType().GetProperties( BindingFlags.Instance | BindingFlags.Public);
        
        foreach (var pi in pis)
        {
            pi.SetValue(p, "f"); //this line creates and assign a new instance (record is immutable)
            Console.WriteLine($"Hashcode AFTER \'{pi.Name}\' property assignment: " + p.GetHashCode());
        }
    }
}




lundi 5 décembre 2022

NoSuchMethodException with List parameter

I am calling a private static method using Java reflection, and that method has as one of its parameters a List. After extensive Googling, I cannot seem to find the right way to get that method for reflection purposes, and I'm getting a NoSuchMethodException when I try to find it:

// In the test file
@Test
@SuppressWarnings("JavaReflectionMemberAccess") // for getDeclaredMethod() call
public void getStringCorrectMessage() {
    try {
        Class<MyException> clazz = MyException.class;
        Method getStringMethod = clazz.getDeclaredMethod( // exception happening here
            "getString", MyEnumObject.class, List.class, Boolean.class);
        getStringMethod.setAccessible(true);
        String actual = (String)getStringMethod.invoke(null, MyEnumObject.VALUE, null, true);
        String expected = "result";
        Assertions.assertEquals(actual, expected);
    } catch (Exception e) {
        Assertions.fail(e.toString());
    }
}

// Package-private static getString() in MyException.java
public class MyException extends Exception {
    static String getString(MyEnumObject myObject, List<String> myList, boolean myBool) {
        return "abc";
    }
}


// Enum class in MyEnumObject.java
public enum MyEnumObject {
    VALUE("blah");

    private final String messageText;
    MyEnumObject(String text) { this.messageText = text; }
    @Override
    public String toString() { return this.messageText; }
}

All the required classes (MyException, MyEnumObject) exist and are imported into the test file properly. I'm also aware that reflection like this would be ugly and awful for anything except internal testing.

My instinct is that the problem is coming from using the simple List.class, but I can't find a solution for a parameterized version despite trying different syntaxes and Googling, so there's either something else wrong or I'm just missing something. If anyone could shed some light on what's going on here, I would very much appreciate it.

Thanks!





Test at runtime if a cast would compile

Given two java.lang.Class objects dst and src and assuming that they represent the types Y and X respectively, I would like a function public static boolean isCastCompilable(Class dst, Class src) that returns true if and only if the statements X x; Y y = ((Y)x); would compile for those types X and Y.

Here is a first attempt at hand-coding these rules:

public class Compilable {

    public boolean isCastCompilable(Class dstClass, Class srcClass) {
        if (Objects.equals(srcClass, dstClass)) {
            return true;
        }
        
        if (Boolean.TYPE.equals(srcClass)) {
            return false; // Boolean cannot be converted explicity to any primitive type:
            // https://javajee.com/casting-of-primitives-in-java
        }

... more code

        return false;
    }
}

For instance, this function would return true for isCastCompilable(java.util.List.class, java.util.ArrayList.class) because the statements java.util.ArrayList x; java.util.List y = ((java.util.List)x); would be valid Java code that a compiler would accept.

It should return false for isCastCompilable(Boolean.TYPE, String.class) because String x; boolean y = (boolean)x; would be rejected by the compiler.

My question: Is there a straight-forward way of implementing isCastCompilable or will I have to handcode all the casting rules myself, the way I started doing in the code example above?

Context: I am making a kind of Java code generator and would like to test if the code that performs casts will compile in order not to emit invalid code.





dimanche 4 décembre 2022

Reflection to avoid class load

I was reading through the PerfMark code and saw a comment about avoid an accidental class load through using reflection in a commit:

if (Boolean.getBoolean("io.perfmark.PerfMark.debug")) {
-          Logger.getLogger(PerfMark.class.getName()).log(Level.FINE, "Error during PerfMark.<clinit>", err);
+          // We need to be careful here, as it's easy to accidentally cause a class load.  Logger is loaded
+          // reflectively to avoid accidentally pulling it in.
+          // TODO(carl-mastrangelo): Maybe make this load SLF4J instead?
+          Class<?> logClass = Class.forName("java.util.logging.Logger");
+          Object logger = logClass.getMethod("getLogger", String.class).invoke(null, PerfMark.class.getName());
..
}

I don't quite understand which class is prevented from being accidentally loaded here. According to Class#forName will cause the logger class to be loaded. From my understanding, the class will only be loaded if the enclosing if condition is true. Or is this the point I am missing?

Commit with more context is here: https://github.com/perfmark/perfmark/commit/4f87fb72c2077df6ade958b524d6d217766c9f93#diff-f9fdc8ad347ee9aa7a11a5259d5ab41c81e84c0ff375de17faebe7625cf50fb5R116


I ran the part with the if block and set a breakpoint on static and non-static fields in the Logger class. It hit the breakpoint only when the call was executed irregardless of using reflection or direct. When the if condition was false, no logger was loaded in any case.





Pass array as input parameter in CSharpScript

I try to run method by CSharpScript.

Method:

public class TaskSolution 
{ 
   public int[] Calculate(int[] inputValue) 
   {
      return inputValue;
   }
}

I tried this solution:

var script = CSharpScript.Create(solution.Code);
var input = new int[3] { 1, 2, 3 };
var call = await script.ContinueWith<int[]>($"new TaskSolution().Calculate({input})").RunAsync();

But it throws Microsoft.CodeAnalysis.Scripting.CompilationErrorException with text "(1,43): error CS0443: Syntax error; value expected" and no more information inside.

When I run similar method but with simple input parameter (as int or string) - it runs successfully. But I meet problems with using arrays.





Dynamic initialization of POCO classes based on DTO class

I want to di initialization only for those classes they are mapped not necesserily 1:1 to dto object class.

I need this in order to generate valid XML file without empty tags (this would be the case if I put ...=new() on each my POCO class and subclass objects)

So if my dto object contains for example:

public class Dto
{
public string? Name {get;set;}
public Foo? Foo {get;set}
public Bar? Bar {get;set}
}

and I have mapping something like:

var model = new Invoice();
var dto = new Dto();
model.ContractDocumentReference!.Id = dto.Foo.RequestId; 
//for example lets say this is a nullable int

model.OrderReference!.Name= dto.Bar.CitizenName;
//have some value "John"

Can I somehow dynamically initialize only OrderReference (because only Bar.CitizenName has actually a value) through reflection?

Is there any other approach? Definitely I would need a map when I initialize some class and when I dont (based on dto class object)





How to get Activity Results outside of Activity Scope

Scenario

I have no access to any sort of scope, consider my code is being called using a ClassLoader, code's in a dex file.

Expectation

Am hoping sort of a Reflection or an Hidden API way to do this.

Possibility

I am not sure but maybe we can use SendIntent, PendingIntent or something like that

Notes

  • The activity is not a FragmentActivity
  • I have no access to any change to current Activity
  • I have Access to everything (READ ONLY)

PS: it's an experiment for knowledge, do not downvote if you think it's duplicate, it's absolutely not. I checked and tried everything on internet.





jeudi 1 décembre 2022

add method dynamically on start of application

I have a class with a method having custom annotation

@Target(ElementType.METHOD)
public @interface MethodXY {
    public int x();
    public int y();
}

public class AnnotationTest {
    @MethodXY(x=5, y=5)
    public void myMethodA(){ ... }

    @MethodXY(x=3, y=2)
    public void myMethodB(){ ... }
}

I want to add N number of methods in this class at run time once when the class loads. The values of X & Y will be read from an array of size N ( any collection / properties file )

I am able to change values of annotation at run time

MethodXY anno2 = (MethodXY) setAttrValue(anno, MethodXY.class, "x", "400");
System.out.println(String.format("New values: %s, %s",  anno2.X(), anno2.y()));

but unable to pass new annotation value to method .

How could it be done in java .





mardi 29 novembre 2022

Rascal MPL dynamically get properties / fields of variable

I often find myself testing using typeOf whenever I'm lost. Is there a similar way to print all properties or fields of a variable, similar to Object.keys (JavaScript) or vars (Python)?





lundi 28 novembre 2022

How can I cast an object to string and use it in a Linq query using Reflection

There's the problem I made an Extension method to IQueryable and I want to get property name and value to do a select on it the thing is that I am using Expression tree and try to search rows by the use of Contain() method which is needs a parameter of type string to do the job. my code is doing well while I do the search over string properties but I want this method to do the search on other types like int, decimal, datetime and even booleans so I need to get the property cast it to string and search for the matching values.

what I tried so far is:

        private static readonly MethodInfo _tostring = typeof(Object).GetMethod("ToString") ?? throw new Exception("Cannot create Method");

        public static IQueryable<T> Search<T>(this IQueryable<T> items, string propertyName, string filterValue)
        {
            MethodInfo _compare =
                (((Expression<Func<string, bool>>)(s => s.Contains("aa"))).Body as MethodCallExpression ?? throw new Exception("Cannot Create Method"))
                .Method;
            var property = typeof(T).GetProperty(propertyName) ?? throw new Exception("Couldn't Get the property");
            var row = Expression.Parameter(typeof(T), "row");

            
            var prop = Expression.Property(row, property);
            // now making sure if the type is string
            if (property.PropertyType != typeof(string))
            {
                //Here I want to cast it to string but the problem is exactly here anything I try feels like a dead end
                prop = Expression.Call(prop, _tostring);
            }

            var func =
                Expression.Lambda<Func<T, bool>>
                (
                    Expression.Call
                    (
                        prop,
                        _compare,
                        Expression.Constant(filterValue)
                    ),
                    row
                );

            return items.Where(func);
        }




How to access list property of derived type through reflection?

Consider this code sample:

public abstract class BaseClass {
    public virtual void DoThing() {
        ...
    }
}

public class DerivedClass {
    public override void DoThing() {
        ...
    }
}

public class SomeClass {
    public List<DerivedClass> MyProp {get; set;}
}

...

// assume we have obj of SomeClass and prop as PropertyInfo of MyProp

var pt = prop.PropertyType;

if (pt.IsGeneric && (pt.GetGenericTypeDefinition() == typeof(List<>)) && (pt.GetGenericArguments()[0].IsSubclassOf(typeof(BaseClass))))
{
    var val = pt.GetValue(obj); // here it is not null 
    var list = val as List<BaseClass>; // list is null
    list?.ForEach(o => o.DoThing());
}

How can I get list of BaseClass and call (probably) overridden method for each of them? As I try to cast property value to list it become null.





dimanche 27 novembre 2022

Reflection - missing 1 parameter

I am using extention function from this post: https://stackoverflow.com/a/72111931/1305993

In my test I have:

@Before
fun setUp() {
    savedStateHandle = SavedStateHandle()
    savedStateHandle["areaId"] = 1L
    saveImageUseCase = Mockito.mock(SaveImageUseCase::class.java)
    repo = FakeRepository()
    viewModel = AreaEditViewModel(repo, savedStateHandle, saveImageUseCase)
}

@Test
fun setUpArea() = runTest {
    viewModel.callPrivateFunc("setUpArea", 2L)
}

In my viewModel I have:

private suspend fun setUpArea(areaId: Long) {
    repository.getAreaById(areaId).first() {
        savedStateHandle["area"] = it
        true
    }
}

When I run test I get: Callable expects 3 arguments, but 2 were provided. java.lang.IllegalArgumentException: Callable expects 3 arguments, but 2 were provided.

I cannot figure out what is that third parameter missing





How to convert string object to generic object at runtime?

Simplify example:

I Have a class with support of direct cast from string

public class MyClass {
    public static explicit operator MyClass(string stringValue) => new MyClass();
    public static MyClass Parse(string value) => new MyClass();
}

I can cast String to MyClass at compile time like (MyClass)"Some value". But when I cast from string to this class type at runtime, I have Invalid cast from 'System.String' to 'SomeNamespace.MyClass'.

How Can I solve this problem? I need to cast from string to generic class at runtime

About Usecase:

This is a parser for runtime text data models. At runtime I have a IList<string> from API that represent Object. I need to convert this IList to my domain Object at Runtime. I can't hardcode concrete class implementation (becouse I only know what object it is at runtime). Here is my implementation, of a generic function that should transform a dictionary of PropertyInfo (of generic object) and Strings (of values from API) to generic object. I think I need some DoDirectCast(Type type, string value) that will direct cast value to type to set parameters of y generic object

public T Transform<T>(Dictionary<PropertyInfo, string> arrOfPropOfT) 
{
    var returnObject = new T();

    foreach (var keyValuePair in arrOfPropOfT) 
    {
        Type propertyType = keyValuePair.value;
        string castableValue = keyValuePair.key;
        object? value = DoDirectCast(propertyType, castableValue);
        propertyInfo.SetValue(returnObject, value)
    }
    return returnObject;
}

I have tried:

var result = Convert.ChangeType("Parsable_string_value", typeof(MyClass));
var converter = TypeDescriptor.GetConverter(typeof(MyClass));
var result = converter.CanConvertFrom(typeof("Parsable_string_value"));

But in both I have an error: Invalid cast from 'System.String' to 'SomeNamespace.MyClass'

So my problem is that String class have no idea how to convert itself to Unknown classes. But all my Unknown classes know how to cast to themselves from String... like (UnknownClass)("Some string value")





samedi 26 novembre 2022

Reflection - private method

In my test I have:

@Before
fun setUp() {
    savedStateHandle = SavedStateHandle()
    saveImageUseCase = Mockito.mock(SaveImageUseCase::class.java)
    repo = FakeRepository()
    viewModel = AreaEditViewModel(repo, savedStateHandle, saveImageUseCase)
    }

@Test
fun setUpArea() = runTest {
    val method = viewModel.javaClass.getDeclaredMethod("setUpArea", Long::class.java)
    method.isAccessible = true
    method.invoke(viewModel, 2L)

...
    }

in my viewModel:

private suspend fun setUpArea(areaId: Long) {
    repository.getAreaById(areaId).first() {
        savedStateHandle["area"] = it
        true
    }
}

when I run my test I get: com.rachapps.area_feature.viewModel.AreaEditViewModel.setUpArea(long) java.lang.NoSuchMethodException: com.rachapps.area_feature.viewModel.AreaEditViewModel.setUpArea(long) at java.base/java.lang.Class.getDeclaredMethod(Class.java:2707) at com.rachapps.area_feature.viewModel.AreaEditViewModelTest$setUpArea$1.invokeSuspend(AreaEditViewModelTest.kt:61)





jeudi 24 novembre 2022

why the autowired bean is null while reflect execute private method and is not null while reflect execute public method?

controller

@Controller
@RequestMapping("/test")
@Slf4j
public class TestController {

    @Autowired
    private ReflectServiceImpl reflectService;

    @PostMapping("/reflectTest")
    @ResponseBody
    public Object reflectTest(@RequestParam String name, @RequestParam String age){
        try {


            Method method = ReflectServiceImpl.class.getDeclaredMethod("reflectTest", String.class, String.class);
//            method.setAccessible(true);
            return method.invoke(reflectService, name, age);

        }
        catch (Exception e){
            log.error("reflectTest出现错误{}", e.getMessage(), e);
        }
        return "error";
    }
}

service

@Service
@Slf4j
public class ReflectServiceImpl extends AbstractReflectService {

    @Autowired
    private ReflectCallService reflectCallService;

    public String reflectTest(String name, String age){
        String s = name + "-" + age;
        log.info("==> {} ==> ???", s);
        return reflectCallService.getName();
    }

    @Override
    public String getCombineData(String name, String age){
        String s = name + "-" + age;
        log.info("==> {}", s);
        return reflectCallService.getName();
    }

    @Override
    public String addressFrom() {
        rainNow();
        return reflectCallService.getName();
    }




}

when ReflectServiceImpl#reflectTest() is public and TestController execute

Method method = ReflectServiceImpl.class.getDeclaredMethod("reflectTest", String.class, String.class);
return method.invoke(reflectService, name, age);

is run right. but when ReflectServiceImpl#reflectTest() is private and TestController execute

Method method = ReflectServiceImpl.class.getDeclaredMethod("reflectTest", String.class, String.class);
method.setAccessible(true);
return method.invoke(reflectService, name, age);

is throw exception

java.lang.reflect.InvocationTargetException: null
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.yichen.casetest.controller.TestController.reflectTest(TestController.java:168)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException: null
    at com.yichen.casetest.test.service.reflect.impl.ReflectServiceImpl.reflectTest(ReflectServiceImpl.java:24)
    ... 59 common frames omitted

other there I have a @Aspect to trigger cglib proxy like below proxy

there is the debug image private method public method

and my test demo is here https://github.com/yichen17/case-test core class => LogAspect、ReflectServiceImpl、TestController

I want to know why there two case have different result and the cause reason.





how to insert a class instance into RTTR sequential view without getting its wrapped value?

All

I am creating a generic binary serializer and got block on how to insert a class instance into a sequential view.

Here is the example code:

#include <iostream>
#include <rttr/type>
#include <rttr/registration.h>
using namespace rttr;

struct Item {
    int i ;
};
struct MyTestClass {
    std::vector<Item> seq;
};

RTTR_REGISTRATION
{
    using namespace rttr;
    registration::class_<MyTestClass>("TestClass")
        .constructor<>()
        .property("seq", &MyTestClass::seq);

    registration::class_<Item>("Item")
        .constructor<>()
        .property("item", &Item::i);

}

void CreateInst(rttr::instance inst) {
    auto localobj = inst.get_type().get_raw_type().is_wrapper() ? inst.get_wrapped_instance() : inst;
    auto p = localobj.get_type().get_property("item");
    p.set_value(inst, 100);
}

int main()
{
    MyTestClass inst;
    for (auto prop : rttr::type::get_by_name("TestClass").get_properties()) {
        auto type = prop.get_type();

        if (type.is_sequential_container()) {
            auto val = prop.get_value(inst);
            auto view =val.create_sequential_view();
            view.set_size(1); //just for demo
            rttr::variant var = view.get_value_type().create();
            CreateInst(var);
            //get its wrapped and insert 'it', it will have the correct result
            //Item it=var.get_wrapped_value<Item>(); 
            view.set_value(0, var);
            prop.set_value(inst, val);
        }
    }
    std::cout << inst.seq[0].i << std::endl;

}

it always output '0' instead of '100' on screen, unless I get its wrapped value and insert. But that is not what I want.

Could any expert help me to improve on this ?

Thank you.

BR Ray





mercredi 23 novembre 2022

Why am I getting a casting error in .NET 7 after using reflection?

Is reflection and casting different in .NET 7 vs .NET Framework? I'm porting a project and getting this casting error after moving the code over. The wierd thing is this class implements that interface. This code works in .NET 4.x.

    foreach (Assembly pluginAssembly in pluginAssemblies)
    {
        try
        {
            // Look for class(s) with our interface and construct them
            foreach (var type in pluginAssembly.GetTypes())
            {
                Type iDesigner = type.GetInterface(typeof(IFireworksDesigner).FullName);
                if (iDesigner != null)
                {
                    object instance = Activator.CreateInstance(type); // creates an object 
                    IFireworksDesigner designer  = (IFireworksDesigner)instance; // throws an exception
                    // do stuff
                }
            }
        }
        catch(Exception ex)
        {
            //Something really bad must have happened. 
            MessageBox.Show("Fatal error reflecting plugins in assembly '" + pluginAssembly.FullName + "'.\r\n" +
                "The error message is:\r\n\r\n" + ex.Message);
        }
    }




mardi 22 novembre 2022

Java 17 reflection: assign the "this" reference of a lambda object

This code runs fine in java 11.

package test;

import org.junit.Assert;
import org.junit.Test;

import java.lang.reflect.Field;
import java.util.function.Consumer;

public class LambdaArg1ReflectionTest {
    @Test
    public void test() throws IllegalAccessException {
        // Create a lambda with reference to parent class (this)
        Consumer<String> lambda = s -> this.parseInt(s, 7);

        // Get the value from the lambdas "this" reference
        Field lambda_arg1_field = lambda.getClass().getDeclaredFields()[0];
        lambda_arg1_field.setAccessible(true);
        Object lambda_arg1_value = lambda_arg1_field.get(lambda);
        // Assert that the value is as we expected
        Assert.assertEquals(this, lambda_arg1_value);

        // Attempt to assign the same value
        lambda_arg1_field.set(lambda, lambda_arg1_value);
    }

    private int parseInt(String s, int i) {
        return Integer.parseInt(s + i);
    }
}

But, in java 17 it throws an exception:

    java.lang.IllegalAccessException: Can not set final test.LambdaArg1ReflectionTest field test.LambdaArg1ReflectionTest$$Lambda$40/0x0000000800c191a8.arg$1 to test.LambdaArg1ReflectionTest

    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:76)
    at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwFinalFieldIllegalAccessException(UnsafeFieldAccessorImpl.java:80)
    at java.base/jdk.internal.reflect.UnsafeQualifiedObjectFieldAccessorImpl.set(UnsafeQualifiedObjectFieldAccessorImpl.java:79)
    at java.base/java.lang.reflect.Field.set(Field.java:799)
    at test.LambdaArg1ReflectionTest.test(LambdaArg1ReflectionTest.java:23)
  • Why?
  • Is it not supposed to work in java 17?
  • Is there any way to work around this?

Obviously this is an example. What the real code attempts to do is to replace the lambdas this reference with a spy object, invoke the lambda and then capture the arguments given to this.parseInt. Ultimately what it does is to serialize the first method invocation of a lambda.





lundi 21 novembre 2022

Having trouble creating this C# method that uses generics to insert into an sqlite table

I am getting a no mapping exists error when I try running this code. Not sure what I need to do here.

public void Create<T>(T obj) where T : IClassModel<T>
        {
            Type type = obj.GetType();
            // get the property names and values of obj
            // PropertyInfo
            PropertyInfo[] properties = type.GetProperties();

            for (int i = 0; i < properties.Length; i++)
            {
                PropertyInfo property = properties[i];
                Console.WriteLine(property);
            }
            
            
            
            // build query as a string (StringBuilder)
            // 1. If you aren't on the last value or column name, you need a comma



            var command = _connection.CreateCommand();

            // use the string you built here
            command.CommandText = $"INSERT INTO {typeof(T).Name} VALUES ($Id, $FirstName, $Surname)";

            command.Parameters.AddWithValue("$Id", obj).SqliteType = SqliteType.Integer;
            command.Parameters.AddWithValue("$FirstName", obj).SqliteType = SqliteType.Text;
            command.Parameters.AddWithValue("$Surname", obj).SqliteType = SqliteType.Text;


            command.ExecuteNonQuery();

That is the create method that I am using. Please, any help is appreciated.





Setting object property by string name

Very new to typescript and am trying to port some C# code. I need to be able to set an instances properties by property string name.

In C# I do this with reflection, but how can I do this in typescript?

The following is a simplified example:

class BaseClazz {
  baseA?: string;
  baseB?: string;
}

class DerivedClazz extends BaseClazz {
  derived1?: number;
  derived2?: number;
  array1?: number[];
  array2?: number[];
}

I want a function that can set the various properties by their string name:

function assign(clazz: BaseClass, propertyName: string, value: any) {
  ...
}

In theory I can call it as follows and each of the 4 properties would be set:

test:BaseClazz = new DerivedClazz();
assign(test, "baseA", "a");
assign(test, "baseB", "b");
assign(test, "derived1", 1);
assign(test, "derived2", 2);
assign(test, "array1", [1, 2, 3, 4]);
assign(test, "array2", [5, 6, 7, 8]);





How to reflect/map models received from frontend into models at backend?

I want to make universal JSON generator for any ViewModel received from frontend. I found here that I can get type from string, but I do not know how to implement this in my case. My idea was to send from Angular array with 2 values, first would be string that say what type is my ViewModel, and second value would be ViewModel, which I need to convert to JSON. (I need this JSONon backend for converting to other file formats, and I have some special requirements, like change of name property, etc.) I am using MediatR, and here are my classes: GenerateJSONQuery is input object, the one I will get from frontend.

 public class GenerateJSONQuery<T> : IRequest<string>
    {
      public string TypeOfList { get; set; }
      public List<T> Data { get; set; }
    }

GenerateJSONQueryHandler is MediatR handler that will do reflection to ViewModel and generate JSON.

public class GenerateJSONQueryHandler<T> : IRequestHandler<GenerateJSONQuery<T>, string>
    {
        private readonly IddeeaODPDbContext _context;
        private readonly IMapper _mapper;
       

        public GenerateJSONQueryHandler(IddeeaODPDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<string> Handle(GenerateJSONQuery<T> request, CancellationToken cancellationToken)
        {
           // logic for generating files, in this part I need to somehow convert 
           // `request.Data` to specific List<T> where
           //  T can be e.g. `NewbornByBirthDateViewModel`, 
           //`IssuedDocumentsViewModel`, `RegisteredVehiclesViewModel`, etc. etc.
        }

Controller that connect IRequest and IRequestHandler is:

public class GenerateFilesController : ApiBaseController
    {
        public GenerateFilesController(IOptions<AppSettings> appSettings) : base(appSettings)
        {

        }

        [HttpPost]
        [SwaggerOperation(Tags = new[] { "Administration/Document" })]
        public async Task<string> List<T>([FromBody] GenerateJSONQuery<T> data, [FromHeader] string Authorization)
        {
            return await Mediator.Send(data);
            
        }

    }

and NewbornByBirthDateViewModel is example VieWModel that I need to serialize into JSON.

public class ClientNewbornByBirthDateViewModel 
    {
    
       [TranslatedFieldName("Identifier", LanguageEnum.EN)]
        public int Id { get; set; }
        public string Institution { get; set; }
       [TranslatedFieldName("Men", LanguageEnum.EN)]
        public int MaleTotal { get; set; }
       [TranslatedFieldName("Women", LanguageEnum.EN)]
        public int FemaleTotal { get; set; }
        public int Year { get; set; }
        public int Month { get; set; }
   }

I am pretty sure that my thinking way is bad, and that I need to do some kind of reflection, but I do not know how. I can not send only type of ViewModel from frontend, and then select all from db with context.Set<T>() because there can be filters, and those filters depends on which ViewModel is selected, so I must pass object with data from frontend to JSONGenerate logic and then reflect it to specific ViewModel on backend.





dimanche 20 novembre 2022

Copy EF Core entity property proxy using reflection

I am trying to make a duplicate of an EF Core entity and then store it in the database. One of the tasks is copying all writable properties. Since I have to make duplicates of many entity types, I am using reflection to copy all properties and not forgetting new ones in the future.


public abstract class BaseEntity
{
    public void CopyAllWriteablePropertiesTo(BaseEntity destination)
    {
        Guard.ArgumentNotNull(destination, nameof(destination));

        if (destination.GetUnproxiedTypeName() != this.GetUnproxiedTypeName())
            throw new ApplicationException("Not same type");
    
        var properties = this.GetType().GetProperties();
        foreach (var property in properties)
        {
            if (property.Name == nameof(Id))
            {
                continue;
            }
    
            if (property.CanWrite)
            {
                Type memberType = property.PropertyType;
    
                try
                {
                    var propValue = property.GetValue(this);
                    var originalType = propValue.GetType();
                    
                                        //PROBLEMS START HERE
                    Convert.ChangeType(propValue, memberType);      
                    var convertedType = propValue.GetType();
                    property.SetValue(destination, propValue);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(ex, $"Error copying {property.Name} at object {this}");
                }
            }
        }
    }

}

With primitive types (string, int...) the process works well, but my entities have references to other entities.

I am using Lazy Loading, so when I read a property of, say DerivedEntity class,


var propValue = property.GetValue(this);

returns a proxy DerivedEntityProxy.

If I try to assign it with


property.SetValue(destination, propValue);

I get an error since types do not match ( setting a proxy object value for a raw entity).


System.Reflection.TargetException: Object does not match target type.

If before assigning I try to cast the proxy to the underlying object, I get an exception


{"Object must implement IConvertible."}

Is there a way to do this?





vendredi 18 novembre 2022

If i use Class.forName with parameter as Example.class , it throws ClassNotFoundException

First of all hello everyone and sory for my bad english :P

I have an problem with Class.forName method. If i use Class.forName with parameter as Example.class , it throws ClassNotFoundException. Then i try without class prefix for example org.example.Example and it worked. How can i solve this problem ?

My basic code and stack trace:

public class Main {
    public static void main(String[] args) throws ClassNotFoundException {
        Class clazz = Class.forName(String.valueOf(EventPublisherContext.class));
        System.out.println(clazz.getSimpleName());

    }
Exception in thread "main" java.lang.ClassNotFoundException: class org.cqs.impl.EventPublisherContext
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:390)
    at java.base/java.lang.Class.forName(Class.java:381)
    at org.cqs.impl.Main.main(Main.java:10)

Actually i solved this problem with basic method, in below:

public static Class getClass(Class clazz) throws ClassNotFoundException {
    List<String> classString = new ArrayList<>();
    String[] g = clazz.toString().split(" ");
    Arrays.stream(g).forEach(val -> {
        classString.add(val);
    });
    classString.remove(0);
    return Class.forName(String.join("", classString));
}

Then i got my expect value:

public static void main(String[] args) throws ClassNotFoundException {
    Class clazz = getClass(EventPublisherContext.class);
    System.out.println(clazz.getSimpleName());
    
    //print EventPublisherContext

How can i solve this problem without any additional method if it is not impossible.





Java dynamically change builtin class behaviour

I have an interesting problem. I would like to change the behaviour of some builtin class dynamically. Here is an example:

I want to change the behaviour of the "get current time" procedure in Java. I want to mock it to return 01-01-2022 12:30 if some condition is true. My intuition tells me that I need to use reflection overwriting + Proxies but I am still not sure which API can give me this flexibility. I don't know two things: What is the method that is being called to get the current time? How to "patch" method's class to be actually my Proxy?

Thanks in advance!

I checked the docs for both reflection and Proxies and I still have no clue on how to proceed.





jeudi 17 novembre 2022

How to find all classes that implement a specific interface using System.Reflection.Metadata

I'm trying to figure out whether I can reliably identify .NET assemblies that contain classes that implement a specific interface. The catch here is that I cannot load assemblies using Reflection because that requires resolving all references of the assembly to be loaded and that is just not possible in my situation.

This is why I attempt to do so using the NuGet package System.Reflection.Metadata because that approach does not seem to require loading referenced assemblies. However, I'm stuck with completing the code so that the interface in question is found. Here's what I have:

namespace ReflectionMetadataTest
{
   using System;
   using System.IO;
   using System.Reflection.Metadata;
   using System.Reflection.PortableExecutable;

   public static class Program
   {
      static int Main(string[] args)
      {
         if (args.Length < 1)
         {
            Console.Error.WriteLine("Please specify a single file path.");
            return 1;
         }

         string filePath = new FileInfo(args[0]).FullName;

         using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
         {
            using (var peReader = new PEReader(fileStream))
            {
               if (!peReader.HasMetadata)
               {
                  return 2;
               }

               MetadataReader metadataReader = peReader.GetMetadataReader();

               foreach (var typeDefinitionHandle in metadataReader.TypeDefinitions)
               {
                  var typeDefinition = metadataReader.GetTypeDefinition(typeDefinitionHandle);
                  var interfaceHandles = typeDefinition.GetInterfaceImplementations();

                  foreach (var interfaceHandle in interfaceHandles)
                  {
                     var interfaceImplementation = metadataReader.GetInterfaceImplementation(interfaceHandle);
                     var whateverThatIs = interfaceImplementation.Interface;

                     // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                     // TODO: How would I find the fully qualified name of the the interface so that I can compare with the name I'm looking for?
                     // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                  }
               }

               return 0;
            }
         }
      }
   }
}

How would I resolve whateverThatIs to an actual type of fully qualified name so that I can then compare it with the type/name of the interface that I'm looking for?





mercredi 16 novembre 2022

C#, trying to create human readable type name

I am trying to generate a human readable string for e.g. ICollection<string> or any other generic ICollection<> / IList<> / IEnumerable<>

In order to do this I use amongst others the following routine:

public static string HumanReadableTypeName(this Type aType)
    {
        if (aType == null)
            throw new ArgumentNullException($"{nameof(ReflectionExtensions)}.{nameof(HumanReadableTypeName)}");
        var lBaseType = Nullable.GetUnderlyingType(aType);
        if (lBaseType != null)
            return cNullableHdr + HumanReadableTypeName(lBaseType);
        if (aType == typeof(string))
            return aType.Name;
        if (aType.IsArray)
        {
            var elementTypeName = HumanReadableTypeName(aType.GetElementType());
            var lBuilder = new StringBuilder(elementTypeName);
            for (var i = 0; i < aType.GetArrayRank(); i++) // add brackets for each dimension
                lBuilder.Append("[]");
            return lBuilder.ToString();
        }
        var listtype = aType.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IList<>)).FirstOrDefault();
        if (listtype != null)
        {
            var itemType = listtype.GetGenericArguments().Single();
            var itemTypeName = HumanReadableTypeName(itemType);
            return $"IList<{itemTypeName}>";

        }
        var collectiontype = aType.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICollection<>)).FirstOrDefault();
        if (collectiontype != null)
        {
            var itemType = collectiontype.GetGenericArguments().Single();
            var itemTypeName = HumanReadableTypeName(itemType);
            return $"ICollection<{itemTypeName}>";

        }
        var enumerabletype = aType.GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEnumerable<>)).FirstOrDefault();
        if (enumerabletype != null)
        {
            var itemType = enumerabletype.GetGenericArguments().Single();
            var itemTypeName = HumanReadableTypeName(itemType);
            return $"IEnumerable<{itemTypeName}>";
        }
        return aType.Name;
    }

Trouble is that when I pass typeof(ICollection<string>) as an argument I get IEnumerable<string> as an answer.

In the debugger I entered:

typeof(ICollection<string>).GetInterfaces()

with as result a collection of just 2 elements:

+       [0] {Name = "IEnumerable`1" FullName = "System.Collections.Generic.IEnumerable`1[[System.String, System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]"}  System.Type {System.RuntimeType}
+       [1] {Name = "IEnumerable" FullName = "System.Collections.IEnumerable"}  System.Type {System.RuntimeType}

So it seems the ICollection<> interface isn't listed!

What confuses me also is that the following statement:

typeof(ICollection<string>).Name

returns:

"ICollection`1"

So the debugger appears to be able to show it is an ICollection of some kind.

Am I overlooking something, is this featured behavior, or is it a bug in VS22 / .NET7

TIA





mardi 15 novembre 2022

Generate Avro schema from C# record

Is there a possibility to generate an Avro schema out of a C# record. I found the Avro.Reflect namespace, which has an AvroFieldAttribute to (I guess) annotate properties, but I can not figure out how to get the schema out of an annotated object.





How do you declare generic type of any "interface" in Java

Given the following example code

package com.test;

import org.reflections.Reflections;
import java.util.Set;

public class Main {
    public interface TestA {}
    public interface TestB {}

    public static class Aclass implements TestA {}
    public static class Bclass implements TestA, TestB {}

    public static <T> Set<Class<? extends T>> getClassesThatImplement(Class<T> interfaceClass) {
        Reflections reflect = new Reflections("com.test");
        return reflect.getSubTypesOf(interfaceClass);
    }

    public static void main(String[] args) {
        Set<Class<? extends TestA>> aClasses = getClassesThatImplement( TestA.class );
        // Prints [class com.test.Main$Aclass, class com.test.Main$Bclass]
        System.out.println(aClasses);

        Set<Class<? extends TestB>> bClasses = getClassesThatImplement( TestB.class );
        // Prints [class com.test.Main$Bclass]
        System.out.println(bClasses);
    }
}

how can I limit my method, getClassesThatImplement to only accept interfaces so that I get compile time errors instead of runtime errors if I use a regular class? There is no common, or "root", interface I can use to "bound" my generic type <T implements ...>. Is there even a way to do that in Java or will I have to rely on runtime checks?





lundi 14 novembre 2022

Adding to a Generic List with Type parameter

Consider the following setup:

class Shelf : ScriptableObject // << IS A SCRIPTABLE OBJECT
{
    [SerializeField] List<Jars> jars = new();

    public AddUniqueJar(Type typeOfJar)
    {
        //need to add a new object of type typeOfJar to jars. I currently do something like this:
       sentences.Add((FlipbookSentence)Activator.CreateInstance(typeOfJar));
       EditorUtility.SetDirty(this);
       AssetDatabase.SaveAssets();
       AssetDatabase.Refresh();
    }
}

abstract class Jar:UnityEngine.Object{} // << NOT A SCRIPTABLE OBJECT

class JamJar:Jar{}

class PickleJar:Jar{}

class MoneyJar:Jar{}

I'd have imagined this would all be fine but the next time my code compiles or restart a session my object forgets what Type of Jar each instance within the list is, or that the instance is anything at all as I'm met with a null reference.

How do I get my method to add a new object of this type to the list while also serializing and maintaining that information between sessions?