mardi 30 avril 2019

How to find interface in assemblies? For plugin system

I am trying to create a plugin system but I get "Object reference not set to object" Error.

I have loaded each dll as a assembly then used Assembly.GetTypes(). I loop through my types to find my IPlugin interface. I then use Activator.CreateInstance() to create a new IPlugin for a reference and add it to my Plugins list.

           foreach(string dll in dllFiles) {
                AssemblyName an = AssemblyName.GetAssemblyName(dll);
                Assembly assembly = Assembly.Load(an);

                Type[] types = assembly.GetTypes();

                foreach(Type type in types) {
                    if(type.GetInterface(PluginType.FullName) != null) {
                        IPlugin plugin = Activator.CreateInstance(type) as IPlugin;
                        Plugins.Add(plugin);
                        Console.WriteLine("Added a plugin!");
                    }
                }
            }


I expect to be able to loop through my Plugins list and call the method "Do()" in each but I get a object reference not set to object.





How to call a function from a delegate and a function pointer inside

I have the code below, calling a function with delegate, and a function inside the delegate. But the system throw a exception of " Cannot marshal 'return value': Invalid managed/unmanaged type combination." in Marshal.GetDelegateForFunctionPointer, could anyone help on how tosolve this?

namespace hello
{ 
    class test
    { 
        public delegate IPAddress[] DnsFuncDelegate(string message);
        public DnsFuncDelegate dns = null;

        static void Main(string[] args)
        {
            BindingFlags anyType = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

            string filePath1 = "I:\\psnet\\System.dll";
            Assembly systemAssembly1 = Assembly.LoadFile(filePath1);
            Type targetMethodClass1 = systemAssembly1.GetType("System.Net.Dns");
            var targetMethodType = new Type[] { typeof(String), };
            MethodInfo target1 = targetMethodClass1.GetMethod("GetHostAddresses", anyType, null, targetMethodType, null);
            RuntimeHelpers.PrepareMethod(target1.MethodHandle);
            IntPtr target1Addr = target1.MethodHandle.GetFunctionPointer();

            DnsFuncDelegate dns = (DnsFuncDelegate)Marshal.GetDelegateForFunctionPointer(target1Addr, typeof(DnsFuncDelegate));

            IPAddress[] addresses2 = dns("localhost");
        }
    }
}





Java Execute a Function from a compiled class

Let's say i have one single compiled .class which doesn't utilize any external libraries, that I've taken from another android app. Can I call a specific function within that compiled class, from my project?





How to prevent instances of subclasses without using the parent class Builder

I have a Class called State inside my library. I have a builder for it inside the class, accessed through State.Builder.build(). I need it to be instantiated only by that builder.

I want others using my library to extend and create their states, like CustomState, but not be able to instantiate those subclasses of State without using State.Builder.

Java doesn't seem to support it in the ways I've tried. if I use a private constructor in State class, the child classes show a compilation error "There is no default constructor available in com.example.State"

if I use a protected constructor, no error, but the subclasses can be instantiated with a simple new CustomState() statement.

if I use no modifier (package level access), still the subclass can be instantiated even if the class it's instantiated from has another package name.

any ideas?

Thanks





Getting Created Instance of A Class With Reflection

I am trying to use singleton objects and trying to set field during application load. But when i try to set field, i am getting class cast exception. Otherwise i am trying to cast but this time i'am using newInstance and i am loosing old instance.

My goal is that creating beans like spring without a constructor. And adding proxy to beans during application load.

--Not: I don't wanna use constructor. Just creating beans like spring.

I tried different solutions

Trying to class

field.set(classObject, object); --> throw Lang.class can not cast my.package.classObject

Trying to create new intsance

field.set(classObject.cast(classObject.newInstance), object); --> creating new intsance and i am loosing singleton programming approach.

And example code

//here i am searching all classes and adding bean and their called classes to list.
static void loadApp() {
    try {
        List<Class> classList = PackageScanner.getClasses(ApplicationProperties.getProperty("app.package"));
        classList.forEach(item -> {
            Annotation[] t = item.getAnnotationsByType(ServiceBean.class);
            if (ArrayUtils.isNotEmpty(t)) {
                ServiceBean bean = (ServiceBean) t[0];
                if (StringUtils.isEmpty(bean.value())) {
                    BeanUtil.addBean(item.getSimpleName(), item);
                } else {
                    BeanUtil.addBean(bean.value(), item);
                }
            }
            for (Field field : item.getDeclaredFields()) {
                Annotation[] a = field.getAnnotationsByType(Bean.class);
                if (ArrayUtils.isNotEmpty(a)) {
                    try {
                        BeanUtil.addField(field.getName(), new AnnotatedFieldModel(item, field));
                    } catch (Exception e) {
                        LOGGER.error("Creatiton error ", e);
                    }
                }
            }
            item.getFields();
        });
    } catch (Exception e) {
        LOGGER.error("Package Reading problem ", e);
    }
}

//I am getting classes from list. I don't have object bcs i didnt create any object yet.
    static void addPrxoy() {
    try {
        BeanUtil.getFields().keySet().forEach(item -> {
            AnnotatedFieldModel annotatedFieldModel = BeanUtil.getField(item);
            Class clazz = BeanUtil.getBean(item);
            Object object = Proxy.newProxyInstance(clazz.getClassLoader(),
                    new Class[]{annotatedFieldModel.getField().getType()},
                    new DynamicInvocationHandler());
            annotatedFieldModel.getField().setAccessible(true);
            try {
                annotatedFieldModel.getField().set(annotatedFieldModel.getClazz(), object);
            } catch (Exception e) {
                LOGGER.error("Bean creation error", e);
            }
        });
    } catch (Exception e) {
        LOGGER.error("Package Reading problem ", e);
    }
}





Using java generic types for type transformation

I have an Object o that can be casted to type A and type B.

I need a function transformForType(Type t, Object o) that takes a type, lets say A or B and checks if o its that type and process it to transform it.
The usage of the function would be something like that: B result = tranformForType(B.class, o);


My question is whats the way to define the tranformForType function, and if its posible whats the best way using generic types.
Regards.





Is it possible to pass command line arguments to a reflectively loaded PE?

I've been interested in reflective PE injection, particularly .exe files. I was wondering, is there a way to pass command line arguments (argc and argv) to a reflectively loaded .exe file?

I've noticed that, as part of the reflective loading process, calling CreateRemoteThread with the lpParameter argument allows for parameters to be passed, but would the reflectively loaded .exe file recognize this as argc/argv?

If not is there a way to hook argc/argv in either the reflectively loaded .exe or the host process in order to present argc/argv to the reflectively loaded guest .exe?





Execute InvocationHandler invoke method for each method at my proxied class

I have implement a dynamic proxy in order to do some operations before my methods started. now I have a problem when invoking two methods from the proxied class, here is the code:

Dynamic proxy class:

public class IPageProxy implements InvocationHandler {

    private Class <? extends IPage> screenClazz;

    public IPageProxy(final Class <? extends IPage> screenClazz) {
        this.screenClazz = screenClazz;
    }

    @SuppressWarnings("unchecked")
    public static <T extends IPage> T getInstance(final Class<? extends IPage> type)
            throws InstantiationException, IllegalAccessException {

        List<Class<?>> interfaces = new ArrayList<>();
        interfaces.addAll(Arrays.asList(type.getInterfaces()));

        return (T) Proxy.newProxyInstance(
                type.getClassLoader(),
                findInterfaces(type),
                new IPageProxy(type)
             );

    }


    static Class<?>[] findInterfaces(final Class<? extends IPage> type) {
        Class<?> current = type;

        do {
            final Class<?>[] interfaces = current.getInterfaces();

            if (interfaces.length != 0) {
                return interfaces;
            }
        } while ((current = current.getSuperclass()) != Object.class);

        throw new UnsupportedOperationException("The type does not implement any interface");
    }





    @Override
    public Object invoke(final Object proxy, final Method method, final Object[] args) throws InvocationTargetException,
            IllegalAccessException, IllegalArgumentException, InstantiationException, ParserConfigurationException, XPathExpressionException, NoSuchFieldException, SecurityException {

        // before method executed this code will be done
        System.out.println("*   Dynamic proxy invoke method executed for " +  method.getName());

        // Invoke original method
        return method.invoke(screenClazz.newInstance(), args);
    }
}

Main class:

public static void main(String[] args) {
        try {
            //IEventDesignDialog a = new EventDesignDialog();
            IEventDesignDialog a  = (IEventDesignDialog)getInstance(EventDesignDialog.class);
            a.getEventType().getShow();

        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }


    @SuppressWarnings("unchecked")
    public static <T extends IPage> T getInstance(final Class<? extends IPage> type) throws InstantiationException, IllegalAccessException {
        return (T) IPageProxy.getInstance(type);
    }

Proxied class:

public class EventDesignDialog implements IEventDesignDialog{


        private String show;


        private String dateAndTimeDisplayFormat;
        private String eventType;


        @Entity(visibileName = "Show")
        public IEventDesignDialog getShow() {
            System.out.println("get show method invokde successfully");
            return this;
        }

        @Entity(visibileName = "Date And Time display format")
        public IEventDesignDialog getDateAndTimeDisplayFormat() {
            System.out.println("get date and time display format method invokde successfully");
            return this;
        }

        @Entity(visibileName = "Event Type")
        public IEventDesignDialog getEventType() {
            System.out.println("get event type method invokde successfully");
            return this;
        }



}

Actual output:

***   Dynamic proxy invoke method executed for getEventType
get event type method invokde successfully
get show method invokde successfully**

as shown invoke method executed only at the first method invocation after initializing the proxy, second method invoked directly, without proxy functionality is done.

my goal is to execute invoke method each time a method appears at my collection is invoked, the expected result should be as shown below.

Expected output:

***   Dynamic proxy invoke method executed for getEventType
get event type method invokde successfully
*   Dynamic proxy invoke method executed for getShow
get show method invokde successfully**

please let me know if more explanations needed.





Get & Set Request Header Key values using Reflection C#

Using Reflection, I am trying to fetch the request headers of .NET Core web app. I could access the Scheme, Method, etc from the Request object as in the below code,

reqObj.GetType().GetProperty("Scheme").GetValue(reqObj, null).ToString();

I couldnt get the headers of the request object(The class linked HttpRequest ). I am using the lines below that tries to get the Headers and I need to get the keyvalue pairs in it.

Object headerObj = reqObj.GetType().GetProperty("Headers").GetValue(reqObj,null);

var items = headerObj.GetType().GetProperty("Keys", BindingFlags.Instance | BindingFlags.Public).GetValue(headerObj,null);

Here I should get the ICollection of strings. But on that line the process is getting crashed. Even i tried to typecast the headerObj to ICollection<KeyValuePair<String,StringValues>> . But trying those things too gives me a crash.

Here I need to print the header keys and values using Reflection.. Also i m trying to add a key value pair in the header using Reflection. How can i achieve these?





lundi 29 avril 2019

Is there a way to call a member in a generic type in Scala

I'm trying to call a member from a generic type and here is an original way to run the function

SourceStruct is the object that I want to replace with something like T.

override def process(t: SourceStruct, runtimeContext: RuntimeContext, requestIndexer: RequestIndexer): Unit = {
        val json = new util.HashMap[String, String]()
        json.put("time", t.rating.toString)
        json.put("userId", t.userId.id.toString)
        json.put("itemId", t.itemId.id)

        requestIndexer.add(request)
      }


when I replace the SourceStruct with T, how can I call the t.userId?

override def process(t: T, runtimeContext: RuntimeContext, requestIndexer: RequestIndexer): Unit = {
      val json = new util.HashMap[String, String]()
//      json.put("userId", t.userId.id)
//      json.put("itemId", t.itemId.id)
//      json.put("rating", t.rating.toString)

      val request = Requests
        .indexRequest()
        .index(index)
        .`type`(indexType)
        .source(json)
      requestIndexer.add(request)
    }

thanks in advance

I can get the member by using

typeOf[T].members.collect {
case m: MethodSymbol if m.isCaseAccessor => m
}.toList

but still no clue about the question above





Using reflection in Java to set a method's parameters

I am trying to achieve something approximating the following:

public class MyClass<E>
{
    protected MyClass(Object[] variables)
    {
        //init
    }

    public MyClass(Comparator<? super E> comp, Object[] variables)
    {
        //init
    }

    public static <K extends Comparable<? super K>, T extends MyClass<K>> 
         T construct(T example, Object[] variables)
    {
        return new T(variables);
    }
}

Where the Object[] variables is not the actual code, but rather a placeholder for whatever the actual parameters for construction are.

Therein lies my question. I have seen plenty of examples, both with and without reflection, of how to do this when the parameters of T's constructor are known ahead of time, and can thus be specified within construct's parameters. However, I would like to be able to do this even when the parameters of T's constructor are unknown. Is there a way to do this?

I don't particularly care if the solution uses reflection or not so long as it works, but reflection seemed the most likely option.

I am fairly new to reflection as a whole, so I apologize if this question is fairly basic.





C# Reflection on a Type Object

To clarify, yes, I do want to list the properties and values of a System.Type object, which is why I'm using "typeof(Type).GetProperties()" instead of "TheTypeObj.GetProperties()".

I'm trying to list all the property names and values of a Type object, but I'm getting an error. This is what I have so far:

using System.Reflection;

public static string list_properties(Type TheTypeObj)
{
    var Str = "\n";
    object Name, Value;
    foreach (var ThePropertyInfo in typeof(Type).GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public))
    {
        Name = ThePropertyInfo.Name;
        Value = ThePropertyInfo.GetValue(TheTypeObj); //this line throws the error
        Str += Name + ": " + Value.ToString() + "\n";
    }
    return Str;
}

When I use it in context:

list_properties((new Object()).GetType());

I get this error:

Value = ThePropertyInfo.GetValue(TheTypeObj);

InvalidOperationException: Method may only be called on a Type for which Type.IsGenericParameter is true.

How do I list the properties and values of a Type object?





C# How to cast from Type without IConvertible using reflection

My returning value of the method CastTo is from the wrong type. The method CastTo has a returning parameter < T >.

The commented line is what it does without using reflection

            //FieldChoice ChoiceProduct = clientContext_temp.CastTo<FieldChoice>(field);
            Type FieldChoiceType = sharepointClient.GetType("Microsoft.SharePoint.Client.FieldChoice");
            object FieldChoice = Activator.CreateInstance(FieldChoiceType, sharepointClient, web.);
            MethodInfo castToMethodInfo = typeclientContext.GetMethod("CastTo");
            MethodInfo genericCastTo = castToMethodInfo.MakeGenericMethod(field.GetType());
            var ChoiceProduct = genericCastTo.Invoke(clientContext, new object[] { field });
            ChoiceProduct = Convert.ChangeType(ChoiceProduct, FieldChoiceType);

Choiceproduct is from the type Field but should be from the type FieldChoice.

The problem is, i can't create an instance of Fieldchoice before the method cause sharepoint just doesn't have a fittable constructor to allow creating it and i can't cast it to the Type with using Convert.changeType cause it doen't have a IConvertible implementation.

Is there any other way i can cast my variable or change the return type of the method?





samedi 27 avril 2019

How do I use reflection to call a non public method with 0 arguments? [duplicate]

This question already has an answer here:

My class has two methods that look like this:

void Update()
void Update(string)

With reflection, I want to call the top one, but when I try this:

            const BindingFlags findFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

            var methodInfo = script.GetType().GetMethod(methodName, findFlags);

I get a AmbiguousMatchException. How do I call the no arg method?





Java load .class received by the application at runtime

I'm working on a Java distributed application for MANET.

For simplicity let's say I have two nodes A and B that are communicating the one with the other by exchanging serialized objects of a class Message available locally to both nodes because defined at development time.

My goal is to define a new feature that let the two nodes to exchange serialized objects of a class received at runtime.

In particular I have a third node C that knows A and B. The node C by using the GUI let the user to specify a .class file that will be sent to A and B. A and B using reflection should be able to load, create, manipulate and exchange objects of this class received at runtime.

My doubt is, should I use the URLClassLoader for A and B to load the .class file at runtime?

Do you think is it better that C sends to A and B a .jar file containing the .class file o directly the .class file?

Regards





vendredi 26 avril 2019

C# how to cast object to runtime type?

How can I cast (or convert, if cast not possible or reasonable) an object into its runtime type? I can get runtimeType using reflection, but can't figure out how to get List<string> using property.GetValue - I know that I could explicitly do as List<String> but this is for a sort-of soft-code engine where the types are not known until runtime.

Any help is appreciated - thanks! (but looking for code solutions please, not "you shouldn't do it this way..." answers)

// trimmed-down example class
class Bus { public List<string> Passengers {get;set;} }

// create new instance of class
var obj = new Bus();

// get property value using reflection
var className = "Bus";
var assemblyName = "MyAssembly";
var listPropertyName = "Passengers";
var property = GetType(obj).GetProperty($"{listPropertyName}");
var runtimeType = Type.GetType($"{obj.GetType().FullName},{assemblyName}");

// returns object, but I want List<string> instead 
// (or whatever it is; could be different types like T, List<T>, etc.
property.GetValue(obj);

// doesn't work, expects compile-time type
property.GetValue(obj) as runtimeType; 





Reflection error converting to Swift 4 in Objective-C properties

Getting error message

Cannot convert value of type 'UnsafeMutablePointer<objc_property_t>?' (aka 'Optional<UnsafeMutablePointer>') to specified type 'UnsafeMutablePointer<objc_property_t?>' (aka 'UnsafeMutablePointer<Optional<OpaquePointer>>')

On this line

let properties : UnsafeMutablePointer <objc_property_t?> = class_copyPropertyList(self.classForCoder, &count)

Full code here

var count = UInt32()
let properties : UnsafeMutablePointer <objc_property_t?> = class_copyPropertyList(self.classForCoder, &count)
var propertyNames = [String]()
let intCount = Int(count)
for i in 0..<intCount {
    let property : objc_property_t = properties[i]!
    guard let propertyName = NSString(utf8String: property_getName(property)) as? String else {
        debugPrint("Couldn't unwrap property name for \(property)")
        break
    }

    propertyNames.append(propertyName)
}





C# Reflection typeof(string).GetMethod("Equals) Ambiguous match on netcoreapp2.2

Trying to get the methodInfo for

string.Equals(string a, string b, StringComparison comparer)

using the following method:

var methodInfo = typeof(string).GetMethod("Equals", new[] { typeof(string), typeof(string), typeof(StringComparison) } );

when running it on .netcoreapp2.2 i get

System.Reflection.AmbiguousMatchException: Ambiguous match found.

Looking at the overloads i cannot find anything matching the same signature.

When running in a project targeting 4.6.1 everything works fine

Question: How can I target the above stated method without being ambiguous?





Init Generic Class Using Reflection Java

I am currently automating a process of a data handler. What I mean with automating is that the DataHandlers are initiated automatically via reflection based on a specific configuration.

But I am on a point where I do not know how I should solve this problem. It is about this peace of code:

Class<?> clazz = classLoader.loadClass(d);
Object values = clazz.getMethod("values").invoke(null);
RSA.addDataHandler(clazz,new DataHandlerSetAdapter<>(values));

I am loading the class via the classLoader and invoking a static method called "values" which returned a bunch of, you have suggested right, values!

Now the problem is with new DataHandlerSetAdapter<>(values)) which has an error in <> because the Object does not know which class to initiate.

Cannot infer arguments (unable to resolve constructor)

Would this code be in C# I would use typeof() but in JAVA there is nothing like this maybe instanceof but I cannot use this at this point. Btw .values() is returning an Array of the same type class (enum).

How can I solve this problem?

//edit

with the method .getReturnType() on the Method I would get the return type but I cannot apply it to the DataHandlerSetAdapter<>





How to decode JSON by reflected class type?

Can't find a way to correct call decode method with reflected class type. Got ambiguous reference error on it.

class EntityTwo: Decodable {
    var name: String = ""
}

class EntityOne: Decodable {
    var value: String = ""
}

struct Entity: Decodable {

    var entity: String
    var payload: Any

    enum CodingKeys: String, CodingKey {
        case entity
        case payload
    }

    init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)

        entity = try container.decode(String.self, forKey: .entity)
        let entityType = NSClassFromString("MyFramework." + entity) as! Decodable.Type

        payload = try container.decode(entityType, forKey: .payload)
    }
}

In background it used to receive different entities from socket:

{
    "entity": "EntityOne",
    "payload": {
        "value": "EntityOneValue"
    }
}

{
    "entity": "EntityTwo",
    "payload": {
        "name": "EntityTwoName"
    }
}

public func websocketMessage(data: Data) {

    let entity = JSONDecoder().decode(Entity.self, from: data)
    ...   
}





jeudi 25 avril 2019

How to dynamically set object's property based on prop name?

I hope it will be clear what I want to do.

I want to fetch data from database based on properties of provided object and then fill those properties with the retrieved data. So, if for example a user defines a class

class Person
{
   public:
      int Id;
      string Name;
};

and then when he calls MyDatabase.Instance.ExecQuery<Person>() it should return Person object filled with information.

What I did is: a user should define the class as following:

class Person : public DBEntity
{
    ENTITIY_PROP(Person , int, Id)
    ENTITIY_PROP(Person , string, Name)
};

The defined macros ensure to add the name and type of the properties to _propsMeta. Now, how do I set object's property based on it's name (see ExecQuery)?

MY INITIAL SOLUTION
I though to add map that maps property to a function that sets the property but I cannot have a map of references to functions with different signatures. Any ideas? If you think I need to change my design to accomplish what I need - let me know.

template <typename T>
void ExecQuery()
{
    static_assert(std::is_base_of<DBEntity, T>(), "a Class should inherit from DBEntity");

    const auto& props = entity->GetPropsMeta();
    auto row = GetData(props);
    T entity = new T();
    for (const auto& colName : row.Columns)
    {
        string val = row[colName];
        // TODO: SET ENTITY'S PROPERTY colName with val
    }
}

#define ENTITIY_PROP(Class, Type, Name) \
        private: \
            int _##Name; \
        public: \
            class Property_##Name { \
            public: \
                Property_##Name(Class* parent) : _parent(parent) \
                { \
                    _parent->SetPropMeta(#Name, #Type); \
                } \
                Type operator = (Type value) \
                { \
                    _parent->Set##Name(value); \
                    return _parent->Get##Name(); \
                } \
                operator Type() const \
                { \
                    return static_cast<const Class*>(_parent)->Get##Name(); \
                } \
                Property_##Name& operator =(const Property_##Name& other) \
                { \
                    operator=(other._parent->Get##Name()); return *this; \
                }; \
                Property_##Name(const Property_##Name& other) = delete; \
            private: \
                Class* _parent; \
            } Name { this }; \
            \
            Type Get##Name() const { return _##Name; } \
            void Set##Name(int value) { _##Name = value; } \

    class DBEntity
    {
    private:
        std::unordered_map<std::string, std::string> _propsMeta;

    public:
        const std::unordered_map<std::string, std::string>& GetPropsMeta() { return _propsMeta; }    
    };





Can IntelliJ be configured to hit a breakpoint in a Java class that is loaded at runtime through reflection?

I have a Java class that is being loaded at runtime through reflection for a Kafka Streams application, configured with passing the name of the class as a String, like this:

streamsConfig.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG,
    "com.company.data.kstreams.Processor.MediaTimestampExtractor");

Then, at runtime, I have validated that it is properly loading and running the specified class. So, that part is working fine.

However, when I put a breakpoint in IntelliJ inside that custom MediaTimestampExtractor class, the debugger never hits it. I can see in the output that it's executing the code in the class, but for some reason, IntelliJ doesn't "know" that the class is being executed. In fact, the class itself shows a warning of:

Class 'MediaTimestampExtractor' is never used

Is there an option in IntelliJ to enable hitting breakpoints in code dynamically loaded by reflection, or a way to configure the breakpoint so that it hits, even if IntelliJ doesn't believe the class is being used?





Given only the full path to a .class file, how can I load its Class object?

I'm working on an application that needs to be able to do some analysis on Java code; some through the text and some through reflection. The user should be able to input a directory and the program will pull all .java and .class files from it. I have no problem with the .java files but when I try getting the class of the .class file it doesn't work.

I've looked at using ClassLoader with URL. What I've been able to find so far has given me this

URL url = this.openFile().toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass(this.path);
return cls;

path is just a string containing the actual path of the .class file in question, e.g. Users/me/Documents/Application/out/production/MyPackage/MyClass.class. From what I understand from my own reading, this method ties me to knowing the package structure of the input, but in general I don't. All I have is the absolute path of the .class file. Is there a way, just using this path (or some simple transformation of it) that I can load into my program the actual MyClass class object and start doing reflection on it?





Check if a class is an instance of list

I need to get all methods in a class that can return a List and then, check for all those method what type of List it is.

I do:

Person person = new Person();
Class c = person.class;
for (Method m: c.getDeclaredMethods()) {
    // this gets me all the getters
    if (m.getParameterTypes().size() == 0) {
        Class<?> returnType = m.getReturnType()
        if (returnType.equals(java.util.List.class)) {
              // Can get here
              // But how to get the class that is used to parameterise the 
              // list.
        }
    }
}

How do I get the Class that is used to parameterise a List?





Is it possible to determine if a class has been loaded without loading it?

This question from 10 years ago (wow!) asks about how to check if a Java class has been loaded without loading the class if it has not been loaded. The accepted answer of using ClassLoader#findLoadedClass via reflection has worked well for me.

However, now that I've updated to Java 11, the system complains about illegal access, stating that the operation will be denied in future releases.

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by foo.Bar(file:/F:/Foo/bin/) to method java.lang.ClassLoader.findLoadedClass(java.lang.String)
WARNING: Please consider reporting this to the maintainers of foo.Bar
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

Is there any other way in Java to check if a class has been loaded without loading it?





Getting the "InvocationTargetException" exception on the line driver=new ChromeDriver();

I am opening the Chromebrowser, and getting the exeption "InvocationTargetException". The code was running properly few days ago. Here is my code

System.setProperty("webdriver.chrome.driver","D:\\Automation\\chromedriver_win32\\chromedriver.exe");
driver=new ChromeDriver();

At the line "driver=new ChromeDriver();" I am getting the "InvocationTargetException" Exception





How do I get the value of a symbol using Scala reflection?

Using Scala reflection, you can get the value of some element within the AST. For example when I want to get the value of some String within the AST I can use the following statement which works perfectly fine:

a.tree.children.tail.collect({case Literal(Constant(id: String)) => id}).head

However, when the value I want to access is a scala.Symbol instead of a String, the statement above does not return the value:

a.tree.children.tail.collect({case Literal(Constant(id: Symbol)) => id}).head

My question: scala.Symbol appears to be something else than a Literal Constant in the AST?





Return neutral type of argument in C#

How do I return an argument's neutral form? Like the following:

object MyMethod(object a) {
    if(a is int)
        return 0;
    if(a is float)
        return 0.0;
    if(a is string)
        return "";
    if(a is char)
        return '';
    (...)
}

The default keyword doesn't seem to be of use in this case.





How to `getClass` of a `case class` without constructing one?

Suppose you have a Scala case class like this:

case class A(a: Int, b: Int)

How to get the Class representation of it, the one you usually get with .getClass?

What does NOT work:

Calling A.getClass will not give you the class information, but rather the accompanying auto-generated object. You can observe it by calling: A.getClass.getDeclaredFields.toList, which will give you this list: List(public static A$ A$.MODULE$) instead of a and b fields.

Calling A(null, null).getClass does work because we instantiate a dummy object, but it's more verbose, feels dirty, and comes at odds with compiler linters like "wartremover".





Use of private class as method parameter using reflection and cast when invoking the method

I know I can instantiate an object of a non-visible class using reflection. That will give me an object of type Object. But can I make a non-visible class visible?

In my case I want to change handleB by modifying a switch-case-statement:

package packageOne;
public class A {
       B b;
   public A(int a) {
       ...
       b = new B(1,2);
       handleB(b);
   }

   handleB(final B b) {
       switch(b.getName()) {
       case "Hello":
           doSomething();
           break;
       case "Foo":
           doSomethingElse();
           break;
       case "Bar":
           doItBetter();
           break;
   }
}

While B is a non-visible class in the same package.

package packageOne;
final class B {
    private String name;
    public B(int one, int two) {
        this.name = ... //whatever
    }
    public String getName() {
        return name;
    }
}

My class resides in another package, but extends A. I want to modify its protected method handleB by copying it and (its caller methods) to My class. Now to call handleB I don't need reflection, because I have that method in my own class. But B is in its parameter list and B is invisible to MyClass.

I'll put the reflection part in its constructor:

package packageTwo;
public class MyClass {
    // private B myB; not possible, since B is invisible
    private Object myB;

    public MyClass() extends A {
        Class<?> c = Class.forName("packageOne.A");
        fBField = c.getDeclaredMethod("handleB");
        fBField.setAccessible(true);

        myB = fBField.get(this);
        // How can I cast myB to type `B` when I don't know what `B` is?
        handleB(myB); //refers to missing type B
   }

   handleB(final B b) { //missing type B
       switch(b.getName()) {
       case "Hello":
           doSomethingElse();
           break;
       case "Foo":
           doItBetter();
           break;
       case "Bar":
           doSomething();
           break;
   }
}

So I need a way to declare a variable and parameter of type B. Is that possible using reflection or any other way? Is there another possibility to modify the package-private method?





Convert a generic type constructor to non generic type constructor

For example, I have class

class TestClass<T>
{
}

I have some method that receives the constructor of this class. I want to invoke that constructor with some generic parameter without calling MakeGenericType and GetConstructor method again.

static void Main()
{
    var ctor = typeof (TestClass<>).GetConstructors().First();
    Invoke(ctor );
}

static void Invoke(ConstructorInfo ctor)
{
    //ctor.Invoke() - it will not work because TestClass has a generic parameter.
    // I want something like ctor.MakeGenericMethod(typeof(int)).Invoke();
}

Is it possible somehow? Thanks!





How to initialize a dynamic class that has a constructor

I have the following class:

public class CustomItem
{
    //....
}

and there are multiple classes which accept CustomClass in their constructor methods. e.g:

public class FirstClass
{
   public FirstClass(CustomItem customItem) { }
}

I am trying to create a generic method which accepts a dynamic class and initialize it. Something like this:

public List<T> MyTestMethod<T>(CustomItem myCustomItem) where T : class, new()
{
   List<T> list = new List<T>();
   foreach(CustomItem myCustomItem in listOfCustomItems)
   {
      T instance = new T(myCustomItem);
      list.Add(T);
   }
   return list;
}

So, that it can be used like:

List<FirstClass> List1 = MyTestMethod<FirstClass>(customItem);
List<SecondClass> List2 = MyTestMethod<SecondClass>(customItem);

The syntax to instantiate T in MyTestMethod is incorrect. Is what I'm trying to do, possible?





mercredi 24 avril 2019

How do I use Scala reflection to find all subclasses of a trait (without using third-party tools)?

Suppose I have a type, Result:

trait Result[+T] {

  def getValue: T

}

and a subtype of that trait, AnyValResult:

class AnyValResult(value: AnyVal) extends Result[AnyVal] {
  override def getValue: AnyVal = value
}

I want to be able to ask Scala's reflection library for all subtypes of the Result[_] type and have it return a collection that includes AnyValResult.

I've seen lots of people ask this question, and all of them seem to say that they did it using third-party tools. This was a few years ago. Short of reverse-engineering the third-party tools, is there a way to do this that was introduced in more recent versions of Scala? I would prefer not to have to reference some random project on Github if I can do it directly with reflection.





C# reflection - set value in windows form button

I have a requirement where i have to create a 52 buttons and set a value to them. So that i am trying to use reflection to set a value to each buttons.

PropertyInfo propertyInfo = this.GetType().GetProperty("button1");
propertyInfo.SetValue(this, Convert.ChangeType("Nishan", propertyInfo.PropertyType), null);

This is how i have initialized my buttons

public System.Windows.Forms.Button button1 { get; set; }

But this throws an exception

System.InvalidCastException: 'Invalid cast from 'System.String' to 'System.Windows.Forms.Button'.'

NOTE

button1.Text = "Nishan";

I want to done this approach in reflection way.

Can i do that?





how to get local variables of a method from another class

I have two classes A and B A class contains a method which has some of the local variables. now I want to fetch their name and data type in the B class. can you please help me with this.

I researched about java reflection. but I found that I can not achieve this by using reflection, as local variables are stored in stack at the runtime. And reflection can only fetch instance or class variables.

for example,

class A{
     method1(){
         variable1;
     }
}
class B{
      method 2(){
           fetch variable1;
       }
}

I want the data type of variable1 as a result.





Windows downloaded DLL Blocked

I have a DLL developed in C# that is used by several other apps of ours loaded by reflection at runtime, DLL is automatically deployed by Jenkins to some servers and other times installed mannually, the problem is that when I download the DLL it gets blocked and cannot be loaded at runtime. I already know that if you right click the DLL file and select properties, a unblock checkbox or button is availiable which allows to resolve the problem manually, but that solutions doesn't sufice for massive deployments, so I'd like to know if someone can suggest doing something (signing the DLL or similar) to be able to deploy it without the blocking problem

Already know that if you right click the DLL file and select properties, a unblock checkbox or button is availiable which allows to resolve the problem manually

Expected result is to download the DLL or deploy via Jenkins and have a normal operations without being blocked





mardi 23 avril 2019

Reflection Utility to Match Only Existing Fields

In my current project, I'm setting up a utility to compare fields generated by any number of application versions to the latest application results. For example, if I send in a document containing "This is a test of the emergency broadcast system," the production version of the application might return something like:

Sample A:

`{
text: "This is a test of the emergency broadcast system",
numWords: 9
}`

The latest stable development version might spit out:

Sample B:

`{
text: "This is a test of the emergency broadcast system",
numWords: 9,
notes: [ "Emergency", "Urgent"],
}`

And the latest build might give something like:

Sample C:

`{
text: "This is a test of the emergency broadcast system",
numWords: 9,
notes: [ "Emergency", "Urgent"],
subSentences: [
               sentence1: { text: "This is a test.",
                            numWords: 4 }
              ]
}`

The utility stores what it expects the application to return and a struct that contains A) the field it is attempting to compare and B) a list of these structs containing any sub fields. For example, I might want to make sure that the text of every subSentence matches. I can do this if I know the name of each field but...

The problem is that, in order to support extensibility, the software uses protobuf, and I must use reflection. I can make no assumption as to the contents of any object an application will return. The only information I have is that list of field names. If I'd like to make sure that the latest build gets the numWords for the entire sentence correct, for example, I'd pass the utility the object provided by the application, and a list of strings containing the entry numWords.

This poses two problems:

  1. The EqualsBuilder provided by the Apache commons (version 3.9 as of writing this) checks every field as default. This isn't useful in my case because if I'm expecting Sample A and only checking numWords and text, the utility should pass it. But EqualsBuilder.reflectEquals(Sample A, Sample B) will not return true, since Sample B has an entirely new field.

  2. EqualsBuilder provides .append() methods to compare only specified fields, which sounds more along what I need... except for nested data objects. The API only supports appending common types, so I can easily only check numWords by doing EqualsBuilder.append(9).isEqual(Sample A), but there's no way to do something like EqualsBuilder.append(subSentence) and use that as a comparison.

So, I think my question boils down to: Is there any way to compare fields based off field names instead of field values? And if not, is there any way to pull out internal structures without knowing anything about them (except that they exist)?





Get pointer to float64 struct field from field name

I'm trying to write a function that returns a pointer to a struct field given the name of the field. Here's what I've currently got. It panics with the complaint reflect.Value.Addr of unaddressable value.

I assume I must be using reflect incorrectly in GetF64CtlAddr() but despite looking at related questions on SO as well reading the doc for reflect and The Laws of Reflection I'm stuck.

https://play.golang.org/p/cg5-wwiYcEv

package main

import (
    "fmt"
    "reflect"
)

type Ctl struct {
    Fval float64
}
// getCtlF64Addr is meant to return a pointer to a float64 Ctl struct field
// Note: err handling not yet implemented. 
func getCtlF64Addr(p *Ctl, field string) (f *float64, err error) {
    r := reflect.ValueOf(p)
    v := reflect.Indirect(r).FieldByName(field)
    x := v.Addr().Interface() // panics
    return x.(*float64), err
}

var State = Ctl{27}

func main() {
    p := &(State.Fval)
    fmt.Println(*p)                          // This succeeds, so State.Fval is addressable
    fp, err := getCtlF64Addr(&State, "fval") // but this panics
    if err != nil {
        fmt.Printf("%x", err)
    }
    fmt.Println(*fp)
}





How do I recursively and reflectively get a list of all possible field name paths?

I am trying to get a collection of string that give me the names of the fields of all my class members, separated by .s. For example:

public class Apple
{
    public Banana MyBanana = new Banana();
    public Cranberry MyCranberry = new Cranberry();
}

public class Banana
{
    public int MyNumber = 5;
    public Cranberry MyCranberry = new Cranberry();
}

public class Cranberry
{
    public string MyString = "Hello!";
    public int MyOtherNumber = 10;
}

public class Demo
{
    public List<string> GetFields(Type Apple)
    {
        //I can't figure this out
        //But it should return a list with these elements:
        var result = new List<string>
        {
            "MyBanana.MyNumber",
            "MyBanana.MyCranberry.MyString",
            "MyBanana.MyCranberry.MyOtherNumber",
            "MyCranberry.MyString",
            "MyCranberry.MyOtherNumber"
        };
        return result;
    }
}

I believe some sort of recursion and reflection are required, but after writing dysfunctional code for hours, I need some help.

The reason I need this, is because I am accessing third party code which uses these file paths as the key to their respective values.

An example of one failed attempt:

    private List<string> GetFields(Type type)
    {
        var results = new List<string>();
        var fields = type.GetFields();
        foreach (var field in fields)
        {
            string fieldName = field.Name;
            if (field.ReflectedType.IsValueType)
            {
                results.Add(fieldName);
            }
            else
            {
                results.Add(field.Name + GetFields(field.FieldType));
            }
        }
        return results;
    }

I have found several related questions, but none of them exactly fit my question, and I was unable to make the jump myself: Recursively Get Properties & Child Properties Of A Class, https://stackoverflow.c"om/questions/6196413/how-to-recursively-print-the-values-of-an-objects-properties-using-reflection, Recursively Get Properties & Child Properties Of An Object, .NET, C#, Reflection: list the fields of a field that, itself, has fields





lundi 22 avril 2019

Calling common methods without a common interface

I have some generated code (i.e. it cannot be changed) that looks something like this.

class Generated1 {
    public String getA() {
        return "1";
    }

    public void setB(String b) {
    }

    public void setC(String c) {
    }

    public void setD(String d) {
    }
}

class Generated2 {
    public String getA() {
        return "2";
    }

    public void setB(String b) {
    }

    public void setC(String c) {
    }

    public void setD(String d) {
    }
}

I am exploring these objects by reflection. None of them implement any common interface but there's many of them and I want to treat them as if they implement:

interface CommonInterface {
    String getA();

    void setB(String b);

    void setC(String c);

    void setD(String d);
}

It certainly should be possible. This is considered perfectly good code

class CommonInterface1 extends Generated1 implements CommonInterface {
    // These are perfectly good classes.
}

class CommonInterface2 extends Generated2 implements CommonInterface {
    // These are perfectly good classes.
}

I suppose what I'm looking for is something like:

private void doCommon(CommonInterface c) {
    String a = c.getA();
    c.setB(a);
    c.setC(a);
    c.setD(a);
}

private void test() {
    // Simulate getting by reflection.
    List<Object> objects = Arrays.asList(new Generated1(), new Generated2());
    for (Object object : objects) {
        // What is the simplest way to call `doCommon` with object here?
        doCommon(object);
    }
}





Is there a way to get the PropertyInfo from a accessor?

Is there a way to retrieve the PropertyInfo of a property if you have its accessor(s), without going through every property and seeing if the accessors match?

e.g.

//This example uses a sample from a obfuscated assembly
public class ObjectInfo
{
    //the property which to get (laid out)
    public int UQIOWVICXJ
    {
        [CompilerGenerated]
        public int get_Id();

        [CompilerGenerated]
        private void HVKXLIREWQ(int num);
    }
}

//retrieve method
public static PropertyInfo GetIdProp()
{
   var get_accessor = typeof(ObjectInfo).GetMethod("get_Id", BindingFlags.Public | BindingFlags.Instance);

   return //the property info via get_accessor;
}

The only way I see of doing this is by calling typeof(ObjectInfo).GetProperties(//All Prop BindingFlags) and then, for each info in the result, check if the get method's name is equal to get_Id.





Load and Unload assembly with dependencies using reflection

I am trying to Load an assembly of Entity Framework Library and calling ToList on one of its property.

Finally I did it. I need to Invoke this on multi databases for applying migration on them.

So I need different Connection String on each call and because they should rub in a loop because there are some file updates and etc, the c# will cache the loaded assemblies and when I changing the Connection String at runtime and refresh the configuration, the migration again applying for first ConnectionString on Loading Assemblies for first time.

I trying MarshalByRef and its failed because my library of EF is not Serialize able . So I can't Load assemblies in different Application Domain.

For your information my project is a win-form application.

Regards





What is the output type from reflection in this code

I have the following method:

public static class ReflectionHelper
{
    public static List<?> FindType<T>()
    {
        var A =
            from Assemblies in AppDomain.CurrentDomain.GetAssemblies().AsParallel()
            from Types in Assemblies.GetTypes()
            let Attributes = Types.GetCustomAttributes(typeof(T), true)
            where Attributes?.Length > 0
            select new { Type = Types };

        var L = A.ToList();

        return L;
    }
}

what is the type of the list?

if I do:

foreach (var l in L) { ... }

it works find and I can go through the types, but dev environment I'm using (Rider) will not provide a type.





dimanche 21 avril 2019

Naming properties at compile time on generic class

I am trying to write a generic class, pass some types to it and then access it via properties.

I have written this code:

class Factory<T1, T2> where T1 : Test, new()
                      where T2 : Test, new()
{
    public T1 FirstType { get; set; }
    public T2 SecondType { get; set; }

    public Factory() 
    {
        FirstType = new T1();
        SecondType = new T2();
    }
}

and I'm using it like this (OtherTest implements Test):

Factory<Test, OtherTest> factory = new Factory<Test, OtherTest>();
factory.FirstType.MyMethod();

Then I can use FirstType and SecondType properties, however if I change the order:

Factory<OtherTest, Test> factory2 = new Factory<OtherTest, Test>();

This would have different behaviour, since FirstType would be OtherTest. I would like to pass instances and be able to write code like this:

Factory<Test, OtherTest> factory = new Factory<Test, OtherTest>();
factory.Test.MyMethod();    //I want to generate properties named after class
factory.OtherTest.MyMethod();

Can I do this in compile time?





PrivateObject Invoke with a string variable

I got a problem when I try to run a private method with PrivateObject

PrivateObject target = new PrivateObject(typeof(ControlMaster));

string name = "CheckTransportJob";
var value2 = target.Invoke(name, new object[] { "" });

will throw exception ControlMaster.CheckTransportJob not found, but if

var value1 = target.Invoke("CheckTransportJob", new object[] { "" });

run everything fine.

what's difference? and how to solve it?





Dynamic class creation with Fields from other classes

Example:

public class MyObject{
    @SerializedName("hello")
    @NotNull @MaxLength(256) @NotEmpty
    private String hello;
}

public class MyOtherObject{
    @SerializedName("world")
    @NotNull @MaxLength(512) @NotEmpty
    private String world;
}

How to dynamically generate a class MyDynamicHelloWorldObject such that it becomes the equivalent of:

public class MyDynamicHelloWorldObject{
    @SerializedName("hello")
    @NotNull @MaxLength(256) @NotEmpty
    private String hello;

    @SerializedName("world")
    @NotNull @MaxLength(512) @NotEmpty
    private String world;
}

Looking for solutions because copying and pasting is going to lead to errors, especially when code is changed in the future.





vendredi 19 avril 2019

Kotlin Companion Object Limitation about Reflection and Inheritance

Assume:

  • I need a lot of companion (static-like) methods for subclasses of Parent
  • I need a lot of method (non-static) for subclasses of Parent
  • I have more than 50 subclasses of Parent
  • clazz and some other fields must compute per class (not instance) due to performance
  • Very Important: Parent and MyCompanion can have complicated logic but subclasses of Parent like Child should be in the simplest form as possible

Question:

how to retrieve correct class name of Child in both below expressions:

Child().printClass()
Child.printClassUsingCompanion()

Code:

open class MyCompanion {
  var clazz = this::class.java.declaringClass.name
  fun printClassUsingCompanion() = println(clazz)
}

open class Parent {
  companion object : MyCompanion()
  fun printClass() = println(clazz)
}

class Child: Parent() {
  companion object : MyCompanion()
}

fun main() {
  Child().printClass()              //output: Parent
  Child.printClassUsingCompanion()  //output: Child
}





Tip: How to filter data class properties by kotlin annotation

Kotlin annotation isn't the same as Java annotations. So work with Kotlin reflection requires a bit different way compare to classic java. Here you can find a way of filtering properties of Kotlin data class by Kotlin annotations

Implimentation of Annotation

@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Returnable

Dummy Data class

data class DataClass(
    val property: String
    @Returnable
    val annotatedProperty: String
)

Exaplem of filter

DataClass("false","true")::class.members.filter {
     it.findAnnotation<Returnable>() != null
}





Can you use reflective injection techniques with .exe files?

I've been reading about reflective DLL injection and the various methods used to implement it. I was just wondering, could you implement reflective DLL injection using an .exe file, or does it have to be a DLL to reflectively inject it?





Caching MethodInfo doesn't improve performance?

We've recently hit some performance issues by excessive/improper use of some reflection API's in our application. I've solved one of the issues which had to do with GetCustomAttribute<T> by caching some stuff. But I'm struggling with improving the performance of another part of our code which uses MethodInfo.Invoke(...).

To explain the whole situation here's some stuff for context. We have a generic interface we use for all our mappers:

public interface IMapper<in TIn, out TOut>
{
    TOut Map(TIn instance);
}

And we have lots of implementations of this interface, like this example:

public class SomeEntityMapper : IMapper<SomeObject, SomeEntity>
{
    public SomeEntity Map(SomeObject instance)
    {
        //Create an instance of SomeEntity and map stuff from the SomeObject instance
    }
}

All the objects that get mapped share an interface:

[ACustomAttribute("somestring")]
public class ConcreteEntity : IEntity
{
    // Properties
}

We have a class that has to find the correct mapper, get the instance from IServiceProvider and invoke the Map method and return the result:

public class MapHelper : IMapHelper
{
    private readonly IServiceProvider serviceProvider;
    private static readonly IEnumerable<Type> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).ToList();
    private static readonly ConcurrentDictionary<string, Type> entityTypeCache = new ConcurrentDictionary<string, Type>();
    private static readonly ConcurrentDictionary<Type, MethodInfo> methodInfoCache = new ConcurrentDictionary<Type, MethodInfo>();

    public TridionComponentHelper(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
    }

    public IEntity GetEntity(SomeObject instance)
    {
        if (instance == null) throw new ArgumentNullException(nameof(instance));

        Type entityType = GetEntityTypeByName(instance.Name);

        Type mapperType = types.Single(t => t.IsClass && t.Name == $"{entityType.Name}Mapper");

        Type mapperInterfaceType = mapperType.GetInterfaces().Single(i => i.Name.Contains("IMapper"));

        var mapperInstance = serviceProvider.GetRequiredService(mapperInterfaceType);
        MethodInfo mapMethod = GetMethodInfo(mapperInstance.GetType());
        var entity = mapMethod.Invoke(mapperInstance, new[] { instance } ) as IEntity;

        return entity;
    }

    private static Type GetEntityTypeByName(string name)
    {
        if (entityTypeCache.TryGetValue(name, out Type cachedType))
        {
            return cachedType;
        }
        else
        {
            var type = types.Single(t => t.IsClass && t.GetCustomAttribute<ACustomAttribute>()?.Name == name);
            entityTypeCache.TryAdd(name, type);
            return type;
        }
    }

    private static MethodInfo GetMethodInfo(Type type)
    {
        if (methodInfoCache.TryGetValue(type, out MethodInfo cachedMethodInfo))
        {
            return cachedMethodInfo;
        }
        else
        {
            var methodInfo = type.GetMethod("Map");
            methodInfoCache.TryAdd(type, methodInfo);
            return methodInfo;
        }
    }
}

We use this MapHelper in another class where we loop through a list of SomeObject and return the mapped entities. I do not know beforehand what the type of the mapper is supposed to be or else I could've used serviceProvider.GetRequiredService<T>() and just called Map directly. So instead I was using the following code at first to retrieve the right instance of the mapper (registered by the Microsoft.Extensions.DependencyInjection DI framework) and changed to the code above after I noticed it caused some performance issues:

///GetEntity method
...
var mapperInstance = serviceProvider.GetRequiredService(mapperInterfaceType);
MethodInfo mapMethod = mapperInstance.GetType().GetMethod("Map");
var entity = mapMethod.Invoke(mapperInstance, new[] { instance } ) as IEntity;
...

As you can see in the full implementation of MapHelper, I cache all the MethodInfo's I retrieve in a ConcurrentDictionary so any subsequent calls can reuse them. But I haven't noticed any (significant) difference in performance between the code caching the MethodInfo's and the one that doesn't. Am I doing something wrong?





C# Performant method caller attribute usage

I am writing a client library for an API that provides both public and authenticated endpoints. I would like to easily denote which endpoints require authentication using attributes. For instance:

public async Task<ApiResponse> GetPublicData()
{
  var request = CreateRequest( "v1/public" );
  return await _httpClient.GetAsync( request );
}

[RequiresAuthentication]
public async Task<ApiResponse> GetPrivateData()
{
  var request = CreateRequest( "v1/private" );
  return await _httpClient.GetAsync( request );
}

private ApiRequest CreateRequest( string endpoint )
{
   var request = new ApiRequest( endpoint );

   // if (caller has RequiresAuthenticationAttribute)
   //    SignRequest( request, _credentials );

   return request;
}

As far as I am aware, the only way I can access whether or not the caller of CreateRequest has a RequiresAuthenticationAttribute is to create a stack frame, find the method via reflection, and then attempt to get the attribute from the MethodInfo. This can be incredibly slow.

Is there any other way to pass this information into the callee that won't kill performance. I know that the requests will always be limited by the response time of the API, but given that it has to do with financial data, being able to fire off requests as soon as possible is a must, and being able to do it in a clean way that involves attributes instead of manually passing parameters would be very nice.





how to Invoke method when not knowing the class of the parameters, error GenericArguments

I was trying to use sharepoint without referencing to the dll in visual studio but use "Assembly.LoadFrom".

static Assembly sharepointClient = Assembly.LoadFrom(@"C:\Program Files\EPLAN\Platform\2.8.3\Bin\Microsoft.SharePoint.Client.dll"); 

I came to the point i need to invoke the "load" method of clientcontext with the webinfo

object clientContext = Activator.CreateInstance(typeclientContext, args);

So i got this to get the value of the property web and invoke it in the method load

PropertyInfo webPropertyInfo = typeclientContext.GetProperty("Web");
object web = (object)webPropertyInfo.GetValue(clientContext, null);
//Load clientcontext
//clientContext.Load(web);
MethodInfo methodInfoLoad = typeclientContext.GetMethod("Load");
object[] args3 = { web };
methodInfoLoad = methodInfoLoad.MakeGenericMethod(typeclientContext);
methodInfoLoad.Invoke(clientContext, args3);

At this point it tells me that args has to be generic but i can't make it generic cause i don't have the class from in the dll of sharepoint. Or am i missing something? How can i make it generic?

Here is the error:

error: GenericArguments[0], 'Microsoft.SharePoint.Client.ClientContext', on 'Void Load[T](T, System.Linq.Expressions.Expression`1[System.Func`2[T,System.Object]][])' violates the constraint of type 'T'.





Exception: DataAnalysis.Reference+<>c__DisplayClass4 is not serializable

I am trying to serialize objects of class Reference at the end of my program. A serialization exception is thrown, which complains that "DataAnalysis.Reference+<>c__DisplayClass4" is not marked as serializable.

Initially I had the two delegates without the Serializable attribute, so I gave it a try, but it didn't change anything. The classes Cacheable and Operation are already marked as Serializable - and in fact the serialization of the both of them worked perfectly fine before I introduced the Reference class.

I don't even know what c__DisplayClass4 means. So I am sorry, but I don't know what other parts of my 1 megabytes+ source code to post here to help you solve the problem, because in the end I would be posting everything.

As I said, everything worked fine before introducing the Reference class. So I am hoping the problem is somehow localized to it.

using System;
using System.Reflection;

namespace DataAnalysis
{
    /// <summary>
    /// Description of Reference.
    /// </summary>
    [Serializable]
    public class Reference
    {
        [Serializable]
        public delegate void ReferenceSetter(Operation op, Cacheable c);

        [Serializable]
        public delegate Cacheable ReferenceGetter(Operation op);

        readonly ReferenceGetter refGetter;
        readonly ReferenceSetter refSetter;

        public Reference(ReferenceGetter getter, ReferenceSetter setter)
        {
            refGetter = getter;
            refSetter = setter;
        }

        public Reference(FieldInfo operationField)
        {
            refGetter = (op => (Cacheable)operationField.GetValue(op));
            refSetter = ((op, value) => operationField.SetValue(op, value));
        }

        public Cacheable this[Operation op]
        {
            get {return refGetter(op);}
            set {refSetter(op, value);}
        }
    }
}





jeudi 18 avril 2019

Get all public fields with values in object of Scala class

How to get all public fields (including inherited) and their values from object of Scala class?

This:

  class A(val a: String)

  class B(val b: String) extends A("a")

  val b = new B("b")

  b.getClass.getFields

returns empty list.





How can I find where a static method should have been called?

public void SomeGoodMethod(Cube cube)
{
  Friends.Show(() => cube.Solve());
}

public void SomeBadMethod(Cube cube)
{
  cube.Solve();
}

I know I can find the hundreds of methods which take a Cube parameter with reflection. How can I find the methods which do not call static method: Friends.Show (at design-time or run-time) ?





How to get source code location from ES6 JavaScript class instance?

I would like to generate some code from my object tree. In order to generate the required import statements, I need to find out the source code location for a given class from a class instance.

I am already able to get the expected name MyClass with

var name = instance.constructor.name;

but not the source code location

'/src/package/myClass.js'

=>How to do so?

For Java it would work like described here:

Find where java class is loaded from





mercredi 17 avril 2019

Ho to invoke Method at runtime without reflection when you don not know class at runtime

My issue is very simple, that can we invoke methods of a class at run time without using reflection specifically at run time in situation like where we have to load tons of data from data base using ORM but in Object Oriented form instead of raw ResultSet.

Now ORM used by my organization is proprietary and what I have seen inside its code that to load data into POJO from data base it uses reflection to set values of fields by invoking getters & setters methods like below code snippet(This is typical solution and most of the ORM follow same)

// somewhere inside my ORM
Object obj = pojo.newInstance();// pojo a Class instance wrapping up original POJO mapping of Table in db

Class type =pojo.getMethod("get"+StringUtils.capitalize(fieldName),Class[0]).getReturnType();

Method m = pojo.getMethod("set"+StringUtils.capitalize(fieldName), new Class[] { paramType });

m.invoke(obj, new Object[] { value });

now here the major issue is with getMethod of class Class, if we check implementation of it inside rt.jar then somewhere we find below code inside Class.class (in rt.jar)

  private static Method searchMethods(Method[] methods,
                                        String name,
                                        Class<?>[] parameterTypes)
    {
        Method res = null;
        String internedName = name.intern();
        for (int i = 0; i < methods.length; i++) {
            Method m = methods[i];
            if (m.getName() == internedName
                && arrayContentsEq(parameterTypes, m.getParameterTypes())
                && (res == null
                    || res.getReturnType().isAssignableFrom(m.getReturnType())))
                res = m;
        }

        return (res == null ? res : getReflectionFactory().copyMethod(res));
    }

this searchMethods is there which is being called by getMethod internally to find method of object.

This is an performance burden because if we have 80 fields in pojo then we have almost 80 getters and 80 setters and in worst case scenario it has to iterate method array for comparison 160 times(80 for getters and 80 for setters)

now if i have to select 6 fields then it has to scan the method array 12 times for getters & setters and if I do select 20 fields then also and so on.

now how to solve this performance issue while maintaining 3 key points
 1. Performance (in terms of iterations)
 2. Less memory usage 
 3. Re-usability

In JPA we have to create different DTOs as per requirement like if we have 6 fields requirement at one side of view then we have to create constructor having 6 fields as parameters and if we need 20 we have to create either new constructor having 20 fields in same DTO or we have to create entire new DTO with those 20 fields while in above approach no constructor needed , new class not required and by method invocation POJO is being utilized everywhere start from dynamic filed selection to update specific fields.

Now I don't want to create multiple DTO or multiple constructors inside POJO instead I want to invoke getter & setters with out reducing performance of my initialization of object via reflection.

So is there another way by which we can invoke on the fly getter and setter methods of POJO without reflection at runtime specially in use case of ORM API? By This I must be keep using my existing ORM rather than switching to Hibernate+JPA





mardi 16 avril 2019

Fail-fast json4s serialisation of sealed trait and object enum when missing serializer

Set up

I have an enumeration defined using sealed trait, and a custom serializer for it:

import org.json4s.CustomSerializer
import org.json4s.JsonAST.JString
import org.json4s.DefaultFormats
import org.json4s.jackson.Serialization

sealed trait Foo
case object X extends Foo
case object Y extends Foo

object FooSerializer
    extends CustomSerializer[Foo](
      _ =>
        ({
          case JString("x") => X
          case JString("y") => Y
        }, {
          case X => JString("x")
          case Y => JString("y")
        })
    )

This is great, and works well when added to the formats:

{
  implicit val formats = DefaultFormats + FooSerializer
  Serialization.write(X) // "x"
}

This is great!

Problem

If the serializer is not added to the formats, json4s will use reflection to create a default representation of the fields, which is extremely unhelpful for these objects that don't have fields. It does this silently, seemingly without a way to control it.

{
  implicit val formats = DefaultFormats
  Serialization.write(X) // {}
}

This is a problematic, as there's no indication of what's gone wrong until much later. This invalid/useless data might be sent around the network or written to databases, if tests don't happen to catch it. And, this may be exposed publicly from a library, meaning downstream users have to remember it as well.

NB. this is different to read, which throws an exception on failure, since the Foo trait doesn't have any useful constructors:

{
  implicit val formats = DefaultFormats
  Serialization.read[Foo]("\"x\"")
}

org.json4s.package$MappingException: No constructor for type Foo, JString(x)
  at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$constructor(Extraction.scala:417)
  at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$instantiate(Extraction.scala:468)
  at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$result$6.apply(Extraction.scala:515)
...

Question

Is there a way to either disable the default {} formatting for these objects, or to "bake" in the formatting to the object itself?

For instance, having write throw an exception like read would be fine, as it would flag the problem to the caller immediately.





I need to rework a method, specifically remove the generic parameter

I have a method that needs a rework, specifically I need to remove the generic parameter in the signature. The method receives a single parameter, which always implements a specific interface.

This is the method:

public void SendCommand(T command) where T : ICommand {
using (var scope = services.CreateScope()) { var commandType = command.GetType(); var handlerType = typeof(ICommandHandler<>).MakeGenericType(commandType);

            var service = scope.ServiceProvider.GetService(handlerType);
            (service as ICommandHandler<T>).Handle(command);
        }

}

The sticking point is the (service as ICommandHandler).Handle(command), line, which receives a type parameter of an object that implements ICommand. Depending on the parameter actual type, the service retrieved is different.

Is there any way to remove the generic parameter, and use the actual type of the parameter as the generic parameter of the ICommandHandler line?





How to make PHP StdClass reflection

I have a function to log php vaiables to the file. There is a section which handles objects elseif(is_object($var))... and it works well with any application objects. BUT it does not work if the variable is objects of StdClass. I dont understand where is the difference between other objects and StdClass object. Here is the code of the function:

function varLog( $var, $log = 'info', $depth = 2, $round = 0)
{
    $logFile = __DIR__ . '/../log/' . $log . '.log';
    file_put_contents( $logFile, '(' . gettype( $var ) . ') ', FILE_APPEND );

    if( in_array( gettype($var), ['integer', 'double', 'string'] ) )
    {
        file_put_contents( $logFile, $var . PHP_EOL, FILE_APPEND );
    }
    elseif( in_array( gettype($var), ['boolean', 'NULL'] ) )
    {
        $var = is_null( $var ) ? 'NULL' : ($var ? 'TRUE' : 'FALSE');
        file_put_contents( $logFile, $var . PHP_EOL, FILE_APPEND );
    }
    elseif ( is_array( $var ) )
    {
        file_put_contents( $logFile, 'length ' . count($var) . PHP_EOL, FILE_APPEND );

        foreach ( $var as $key => $val )
        {
            file_put_contents( $logFile, str_repeat('    ', $round + 1) . $key . ' => ', FILE_APPEND );
            if ( $round + 1 <= $depth )
            {
                varLog( $val, $log, $depth, $round + 1 );
            }
            else
            {
                file_put_contents( $logFile, '(' . gettype( $val ) . ')' . PHP_EOL, FILE_APPEND );
            }
        }
    }
    elseif ( is_object( $var ) )
    {
        file_put_contents( $logFile, get_class( $var ) . PHP_EOL, FILE_APPEND );
        $props = (new ReflectionClass( $var ))->getProperties();
        foreach ( $props as $prop )
        {
            $prop->setAccessible( true );
            $scoope = $prop->isPrivate() ? '(private)' : ($prop->isProtected() ? '(protected)' : '(public)');
            file_put_contents( $logFile, str_repeat('   ', $round + 1) . $scoope . ' ' . $prop->name . ' => ', FILE_APPEND );
            if ( $round + 1 <= $depth )
            {
                varLog( $prop->getValue( $var ), $log, $depth, $round + 1 );
            }
            else
            {
                file_put_contents( $logFile, '(' . gettype( $prop->getValue( $var ) ) . ')' . PHP_EOL, FILE_APPEND );
            }
        }
    }
}

It seems the line

$props = (new ReflectionClass( $var ))->getProperties();

does not return any props.





Manipulating coordinate data in an array

I have an array of data, the second dimension of which is landmark coordinates derived from paired images. I need to reflect (by multiply -1) either the y or z axis coordinates for a certain number (but not all) of my images to run further morphometric analyses (allows me to superimpose left and right sided shapes). I suspect this is relatively easy, but I'm new to R and haven't been able to figure it out. Example of what I've tried:

df$coordinates [ , 2, 1:10] *-1 # an attempt to reflect the second coordinate colunn in images 1 through 10. This just extracts the data from the array.

I apologise for my ignorance and appreciate any assistance.





ClassNotFoundException when reflecting JavaFx fat jar file

Being new to reflection, I am trying to implement a simple plugin architecture that loads plugins (fat jars) using Reflection.

I have two JavaFx applications (simple demo from org.codehaus.mojo.archetypes:javafx) named myPlugin and myHost. For simplicity, I haven't used any plugin interfaces.

Getting to the code:

>> myPlugin project

com.plugin.MainApp.java

package com.plugin;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));

        Scene scene = new Scene(root);
        scene.getStylesheets().add("/styles/Styles.css");

        stage.setTitle("JavaFX and Maven");
        stage.setScene(scene);
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        printArgs(args);
        launch(args);
    }


    public static void printArgs(String[] args){
        for (int i = 0; i < args.length; i++){
            System.out.println("PLUGIN: " + args[i]);
        }
    }

}

The output of myPlugin project is packaged in myPlugin.jar which resides in C:// directory (I used Intellij IDEA Artifacts builder). The jar file runs simply by following command without any problems around identifying main class or etc: java -jar myPlugin.jar

>> myHost project

com.host.MainApp.java

package com.host;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class MainApp extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));

        Scene scene = new Scene(root);
        scene.getStylesheets().add("/styles/Styles.css");

        stage.setTitle("JavaFX and Maven");
        stage.setScene(scene);
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        launch(args);
    }
}

I want to run myPlugin when button clicked in host. so, the runPlugin method is responsible for reflecting:

com.host.FXMLController.java

package com.host;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;

public class FXMLController implements Initializable {

    @FXML
    private Label label;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("HOST: You clicked me!");
        this.runPlugin();
        System.out.println("HOST: After running plugin!");


    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

    public void runPlugin(){
        try {

            URLClassLoader child = new URLClassLoader (
                    new URL[] {new URL("file:///C:/myPlugin.jar")}, ClassLoader.getSystemClassLoader());

            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(child, child.getURLs()[0]);

            Class<?> mainClass = Class.forName("com.plugin.MainApp", true, child);
            Object instance = mainClass.newInstance();
            Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
            mainMethod.setAccessible(true);

            String[] args = new String[]{"message", "from", "host"};
            mainMethod.invoke(null, new Object[] {args});

        }
        catch (InvocationTargetException e){
            e.printStackTrace(); }
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        }  catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

By clicking button in myHost app, the main method of myPlugin is executed and args sent from host are printed, which means that MainApp class and its main method are loaded successfully by class loader. But when launching the view in myPlugin (launch(args)), I get java.lang.ClassNotFoundException: com.plugin.MainApp exception, which doesn't make any sense to me.

The exact output from stack trace is as follow:

HOST: You clicked me!
PLUGIN: message
PLUGIN: from
PLUGIN: host
java.lang.reflect.InvocationTargetException
    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.host.FXMLController.runPlugin(FXMLController.java:49)
    at com.host.FXMLController.handleButtonAction(FXMLController.java:22)
    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 sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8413)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
HOST: After running plugin!
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: com.plugin.MainApp
    at javafx.application.Application.launch(Application.java:260)
    at com.plugin.MainApp.main(MainApp.java:30)
    ... 64 more
Caused by: java.lang.ClassNotFoundException: com.plugin.MainApp
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at javafx.application.Application.launch(Application.java:248)
    ... 65 more

If the problem is from Reflection, the main method in myPlugin would not be executed. Referencing static method and passing parameters is also correct. Packaging myPlugin into fat jar file seems also correct because extracting it gives me the resources/styles files and folders too, which means all dependencies are resolved.

I mentioned these, because most of similar questions are about reflection problems and packaging .

What am I doing wrong?

Since reflecting a simple console-based plugin works like a charm (I have tested), are there any important differences that should be considered when dealing with gui-based plugins?

I would appreciate any helps.





How can I reflect a process I built with getRuntime.exec?

I have to reflect a program so I can use it's fields and methods. My current project does this with URLClassLoader. I cant use this though, I need an alternative.

            Process p = Runtime.getRuntime().exec("\"C:\\Program Files (x86)\\Java\\jre1.8.0_201\\bin\\java.exe\" -Dcom.jagex.config=http://oldschool1.runescape.com/jav_config.ws -jar C:\\Users\\Administrator\\jagexcache\\jagexlauncher\\bin\\jagexappletviewer.jar \"oldschool\"");
            Thread.sleep(20000);
            Field field = p.getClass().getDeclaredField("client");
            field.setAccessible(true);
            System.out.println("This is the field: " + field);





Java - Read array parameters of the class level annotation

I struggle with reading the parameters of the RequestMapping annotation (in result, it doesn't matter what annotation it is). The point is the annotation is placed on the class level.

@RequestMapping(value = "VIEW", params = "moduleCode=" + MyController .MODULE_CODE)
public class MyController {

}

The way I use to obtain those values is briefly described as the answer to a question here.

for (Annotation annotation : MyController.class.getAnnotations()) {
    Class<? extends Annotation> type = annotation.annotationType();
    System.out.println("Values of @" + type.getName());
    for (Method method : type.getDeclaredMethods()) {
        try {
            Object value = method.invoke(annotation);
            System.out.println("-> " + method.getName() + ": " + value);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

The output is the following:

Values of @org.springframework.web.bind.annotation.RequestMapping
-> value: [Ljava.lang.String;@13b1a47
-> method: [Lorg.springframework.web.bind.annotation.RequestMethod;@4f3a2bf2
-> params: [Ljava.lang.String;@741b4580
-> produces: [Ljava.lang.String;@2a70120d
-> headers: [Ljava.lang.String;@23b1293f
-> consumes: [Ljava.lang.String;@440af967

How can I read array parameters of the class level annotation?





How to search assemblies for types that implement desired generic interface

I am searching through assemblies to identify any classes that implement a desired generic interface so I can dynamically instantiate an instance. This is the code I'm using:

var types = assembly.GetTypes();
var assemblyFormatters = types.Where(type => type.GetInterfaces().Any(i => 
   i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IInterface<>)));

The code works for a standard class:

public class Implementation : IInterface<object>

but not for a generic class:

public class GenericImplementation<T> : IInterface<T>

Event stranger, the code works successfully when run in the intermediate window, but not when run within a unit test framework. The immediate window returns 2 types, the test code run under the debugger returns only the non generic implementation.

I would expect both types to be returned by the code





Exception on retrieving an Integer field value using Reflection

I am on JDK 1.8 and trying to retrieve the value of a field, which is marked as Integer and not int.

I can't change Data Type to int because this class is used by Lucene and an OR/M, so I can only use Reflection to play with it

private Integer fee;

public Integer getFee() {
    return fee;
}

public void setFee(Integer fee) {
    this.fee = fee;
}

When I do the following:

Field field = myClass.getClass().getDeclaredField("fee");
field.setAccessible(true);
Integer fee = field.getInt("fee");

I get this exception:

java.lang.IllegalArgumentException: 
Attempt to get java.lang.Integer field "com.xyz.models.MyModel.fee" 
with illegal data type conversion to int





Use string of class name to new a class

I want to use a class name sting to new a class

NameSpace is Mcs.ControlMaster

Class Name is HostTransportCommand

after check some posts here. I use Activator

var msg = Activator.CreateInstance(Type.GetType(“Mcs.ControlMaster.HostTransportCommand”, true));

got exception

System.TypeLoadException
  HResult=0x80131522
  Message=Could not load type 'Mcs.ControlMaster.HostTransportCommand' from assembly 'Mcs.ControlMaster.UT, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

OKAY, the execution assembly is Mcs.ControlMaster.UT now 。and this class is in Mcs.ControlMaster. then

string fileToLoad = @"Mcs.ControlMaster.exe";
AssemblyName assamblyName = AssemblyName.GetAssemblyName(fileToLoad);
// assamblyName={Mcs.ControlMaster, Version=3.0.19.320, Culture=neutral, PublicKeyToken=null}
AppDomain myDomain = AppDomain.CreateDomain("MyDomain");
//myDomain={System.Runtime.Remoting.Proxies.__TransparentProxy}
Assembly myAssambly = myDomain.Load(assamblyName);
//myAssambly={Mcs.ControlMaster, Version=3.0.19.320, Culture=neutral, PublicKeyToken=null}
var myFunc = myAssambly.CreateInstance("HostTransportCommand");
// myFunc = null

if use

Type.GetType(“Mcs.ControlMaster.UT, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”, true));

will get

System.IO.FileLoadException: 'The given assembly name or codebase was invalid. 

How to solve this issue?





Is it possible to return data set instead of any mapped model class in MyBatis?

I have scenario where I want to make dynamic query which myBatis supposed to support like as below :


    <select id=“someRecords” resultMap=“someRecordMap”>

        DROP TABLE IF EXISTS TEMP_TABLE;
        CREATE TEMPORARY TABLE TEMP_TABLE(some_stub UUID);

        INSERT INTO TEMP_TABLE (some_stub)
        select regexp_split_to_table(#{someIds},',')::uuid;

        SELECT wil.some_identifier_stub as identifier_stub
        ,wil.x
        ,wil.y
        ,wil.z
        ,wil.u
        ,wil.o
        ,msg.p
        FROM TABLE_A msg
        INNER JOIN TABLE_B wil ON msg.a_id = wil.b_id
        INNER JOIN TABLE_C est ON est.c_stub = wil.b_stub
        WHERE wil.unique_id = #{uniqueId} AND wil.b_type_id = #{b_TypeId}
        <if test="environment != null">
            <include refid="environmentCondition"></include>
        </if>
    </select>

    <sql id="environmentCondition">
        AND environment = #{environment}
    </sql>


But instead of someRecordMap, I want to return DataSet so that it become backward compatible with my existing code

So instead of suing myBatis XMl approach I just make custom approach using reflection and annotations like below :

Section : Dynamic Query Based on some condition like IGNORE_SOME_JOIN, IGNORE_SOME_STUB, IGNORE_SOME_EXT_FLAG


    @SqlQueries({@SqlQuery(name = "query1",
                query = "select a,b," +
                        "c,d,e,f,g,wil.h," +
                        " j,h,i " +
                        START_DELIMITER + " " + IGNORE_SOME_JOIN + " " +
                        " ,some_message" + END_DELIMITER +
                        " FROM  A_TABLE wil " +
                        START_DELIMITER + " " + IGNORE_SOME_JOIN + " " +
                        "LEFT OUTER JOIN B_TABLE wim on" +
                        " wil.unique_id = wim.unique_id" +
                        " and wim.created_date >= ?  and wim.created_date <= ?  " + END_DELIMITER +
                        " WHERE ( wil.created_date >= ? AND wil.created_date <= ? AND wil.primary_id = ? " +
                        START_DELIMITER + " " + IGNORE_SOME_STUB + " " +
                        " AND wil.unique_identifier_stub = ?::uuid " + END_DELIMITER +
                        START_DELIMITER + " " + IGNORE_SOME_EXT_FLAG +
                        " AND wil.some_ext_success_flag = ANY(?) " + END_DELIMITER + ")" +
                        "ORDER BY wil.created_date OFFSET ? LIMIT ? ")}
        )


parsing logic for dynamic query be like :


    abstract class ReportingQuery {
        private static final Logger LOG = LoggerFactory.getLogger(ReportingQuery.class);

        static final String START_DELIMITER = "#~";
        static final String END_DELIMITER = "#~";
        static final String REPLACEABLE_DELIMITER = "--";

        /**
         * Responsible to prepare final query after applying dynamic query criteria
         *
         * @param className     : ReportingQuery class reference
         * @param methodName    : Query method name
         * @param queryName     : Dynamic query
         * @param ignoreStrings : Criteria to be applied in dynamic query
         * @return : final static query after applying dynamic query criteria(ignoreStrings)
         */
        static Optional<String> getQuery(Class className, String methodName, String queryName, List<String> ignoreStrings) {
            StringBuilder builder = new StringBuilder();
            try {
                Method[] methods = className.getDeclaredMethods();
                Optional<String> queryString = Optional.empty();
                if (Arrays.stream(methods).anyMatch(x -> x.getName().equals(methodName))) {
                    QueryExample.SqlQuery[] sqlQueries = Arrays.stream(methods)
                            .filter(x -> x.getName().equals(methodName))
                            .findFirst().get().getAnnotation(ReportingQuery.SqlQueries.class).value();
                    if (Arrays.stream(sqlQueries).anyMatch(x -> x.name().equals(queryName))) {
                        queryString = Optional.of(Arrays.stream(sqlQueries).filter(x -> x.name()
                                .equals(queryName)).findFirst().get().query());
                    }
                }

                String[] token = new String[0];
                if (queryString.isPresent()) {
                    token = queryString.get().split(START_DELIMITER);
                }


               ...... SOME logic to make query based on some dynamic condition

            return Optional.of(builder.toString());
        }

        /**
         *
         */
        @Retention(RetentionPolicy.RUNTIME)
        @Target({ElementType.METHOD})
        @interface SqlQuery {
            String name();

            String query();
        }

        /**
         *
         */
        @Retention(RetentionPolicy.RUNTIME)
        @Target({ElementType.METHOD})
        @interface SqlQueries {
            SqlQuery[] value();
        }
    }


So if I have condition IGNORE_SOME_JOIN then my final query with logic would be like


    select a,b,c,d,e,f,g,wil.h,j,h,i FROM  A_TABLE wil WHERE ( wil.created_date >= '2018-08-29T15:15:42.42'
            AND wil.created_date <= '2018-08-30T15:15:42.42' AND wil.acct_id = 2000017
             AND wil.unique_identifier_stub = 'a004f322-1003-40a7-a54b-f3b979744fd2'
             AND wil.some_ext_success_flag  = ANY('{"0","1"}')) ORDER BY wil.created_date OFFSET 0 LIMIT 500;


So with above I got query as string and I'll run below code and get Result Set :


     PreparedStatement ps = con.prepareStatement(query)) {
                    prepareStatement(prepareStatementAndQueryList, ps, con);
                    try (ResultSet rs = ps.executeQuery()) {
                    DO SOMETHING WITH RESULT SET NOW
    }
    }


But I want to do this with MyBatis instead my own custom solution which would little error prone and might be not performance efficient as I have used much reflection here.