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 .