mercredi 31 mai 2017

Add OData Route During Runtime

Is it possible to add OData Routes after the program is compiled? For example, if I want to be able to get a property without using $select, I would need to add the attribute [ODataRoute("Controller({key})/Property")] to the GET method. If I use reflection to get all of the property names, is it possible to create an ODataRoute like the above example without explicitly doing so in an attribute?





How to Invoke Method

please bare with me as this is my first post on SO I hope the code snipped illustrates my issue.. I need to Invoke the CallEvent method like it is in the outcommented line.. i have no access to the ThirdParty or AnotherThirdParty class This is as far as i come

public class ThirdParty
{
    private struct MsgType
    {
    }

    private static void AnotherFunc(MsgType msg)
    {
    }
}

public class AnotherThirdParty
{
    public static void CallEvent<T>(Func<int, Action<T>> action, T arg)
    {
    }
}


public class MyClass
{
    public static void Main()
    {


        Type MsgType = typeof(ThirdParty).GetNestedType("MsgType", BindingFlags.Instance | BindingFlags.NonPublic);
        object msg = Activator.CreateInstance(MsgType);

        MethodInfo CallEvent = typeof(AnotherThirdParty).GetMethod("CallEvent");
        CallEvent = CallEvent.MakeGenericMethod(MsgType);

        MethodInfo AnotherFunc = typeof(ThirdParty).GetMethod("AnotherFunc", BindingFlags.Static | BindingFlags.NonPublic);

        CallEvent.Invoke(null, new object[] {???, msg});
        //CallEvent<MsgType>((int x) => new Action<MsgType>(AnotherFunc), msg);  // i cant get my head around how to solve this (Action<msgtype>)
    }
}

I also tried: CallEvent.Invoke(null, new object[] { new Func> ( (int x) => new Action((object y) => AnotherFunc.Invoke(null, new object[] { y })) ), msg });

but this thorws: System.ArgumentException: Object of type 'System.Func2[System.Int32,System.Action1[System.Object]]' cannot be converted to type 'System.Func2[System.Int32,System.Action1[ThirdParty+MsgType]].

Im out of ideas :(





How to load 2 versions of the same Jar in 1 class Java

This is a complicated question but I will do my best to describe my problem.

I need to load 2 versions of the same JAR in a top level class (v1.jar and v2.jar) so I have access to both versions of the jar. The reason for this is because I want to test if any feature in v2.jar has regressed from v1.jar

In my top level class, I want to call methods of v1.jar and v2.jar and then validate the output from v1 against v2 output. This way I can be certain nothing got screwed up.

I can't import v1 and v2 jars as maven dependencies since this will create a version conflict in maven and by default maven will use the newest jar. So I thought about creating a common interface and having 2 different implementation classes of that interface. Then in the toplevel I can use class loaders to load v1 and v2 jars, etc. But this way not work since I would have to change production v1.jar to implement the common interface.

Any help or insight will be much appreciated. I'd very much like to see samples if possible. And please don't refer me to other threads





What is the proper way to access @hide member from my jar?

My java code need to access a @hide member defined in ViewTreeObserver.java. this hidden member is stable from very old release of android to the last 25, so i don't think it's too much risky (but i don't know, anyway i have no other choice). I can use reflection but it's seam a little over complicated.

i was thinking to add to my jar a dumy ViewTreeObserver.java removing the @hide from the code and compile my app like this. it's seam to work, when i call the hidden member, it's not the code in my dumy java that is executed but the code of android but i don't know if it's a good way because it's look too much easy.

other idea is to create a dumy jar with the dumy ViewTreeObserver.java, in this way i can compile my jar and can deploy it.

so what is the proper way (if their is one) to access @hide member ?





resolve Type in different assembly when it cannot be found

I have several assemblies used as plugins. They were compiled against an assembly -- Common.dll -- that contained shared code across all the plugins. Recently this Common.dll has been split into Common.A.dll and Common.B.dll, and so Common.dll no longer exists.

When loading a plugin, Common.dll can be resolved to to something else (e.g., Common.A.dll) via the AppDomain.AssemblyResolve event. But when calling methods in the plugin that require something from Common.B.dll those types cannot be found.

I'd like to specify the assembly for these types that are not found. Is this possible? AppDomain.TypeResolve seems only to work for dynamic assemblies.





PHP: get property default value constant name using Reflection API

I need to be able to retrieve property default value constant name. For example, having such class:

class Foo
{
    const BAR = 'BAR';
    private $baz = self::BAR;
}

I want to be able to do something like follows:

$reflection = new \ReflectionClass(Foo::class);
$reflection->getProperty('baz')->getDefaultValueConstantName(); // 'Foo::BAR'

The weird thing about PHP Reflection API is that \ReflectionParameter class has method getDefaultValueConstantName(), but \ReflectionProperty does not. I can get property default value using \ReflectionClass::getDefaultProperties(), but this method will return property default value, not constant name this value has been taken from. Is there any solution for getting property default value constant name, and is this feature at least planned for next releases of PHP?





deserialize JSON into dymanically loaded class file

I have generated POJO's from Schema in JSON response, compiled and loaded the class generated from POJO's but at the time of deserialization of JSON response I don't have the actual class to which I can deserialize.

MyClassLoader classLoader = new MyClassLoader(POJOGeneratorForJSON.class.getClassLoader());

Class parentJsonClass = classLoader.loadClass(topLevelclassName, classpathLoc);

ObjectMapper mapper = new ObjectMapper();

byte[] jsonBytes = generator.getBytesFromURL(source);

System.out.println("jsonBytes:"+jsonBytes);

if(jsonBytes != null){

    Object jsonObj = parentJsonClass.newInstance();
    jsonObj = mapper.readValue(jsonBytes, Class.class);
}

Exception I am getting is:"com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Class out of START_OBJECT token"

I know that in the mapper.readValue() I need to provide the actual class as second argument, but dont know how.





Copy all event handlers from one control to another at runtime

I'm trying to copy every event handlers from one control to another (same type). I found several exemple to do it with Winform but nothing for WPF...

<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://ift.tt/o66D3f"
    xmlns:x="http://ift.tt/mPTqtT"
    xmlns:d="http://ift.tt/pHvyf2"
    xmlns:mc="http://ift.tt/pzd6Lm"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">

    <StackPanel x:Name="panel">
        <Button x:Name="btn1" 
                Content="Button 01"/>
    </StackPanel>
</Window>


using System;
using System.Windows;
using System.Windows.Controls;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            btn1.Click += (s, e) => Console.WriteLine("Button pressed");

            AddButton();
        }

        private void AddButton()
        {
            Button btn2 = new Button() { Content = "Button 02" };
            panel.Children.Add(btn2);

            // Copy all event handler from btn1 to btn2 ??
        }
    }
}

The thing is that I don't have access to any handlers method name, as i'm suppose to copy the event handlers from another class...





How to grant access on all private fields values retrieved by reflection?

Is it possible to get a fields' value, without using field.setAccessible(true);?

 Field field = object.getClass().getDeclaredField(fieldName);    
 field.setAccessible(true);
 Object value = field.get(object);

I mean, could I simply grant access to all private fields of a specific class, without having to invoke the setter on each read?





JavaScript OOP and Reflection - Are there any ways to call a private method from outside a class itself?

Are there any ways to call a private method from outside?

Please don't ask why i need this.

Just my personal curiosity and trust in power of doing anything in JS :)

function Module () {

  var privateMethod = function () {
    alert('1');
  };

  var publicMethod = function () {
    privateMethod();
    alert(2);
  };

  return {
    pm: publicMethod
  };
}

var m = new Module();
m.pm(); // can i call m.privateMethod() here somehow?





Is it possible to check that class has static block (via reflection or other ways)?

For testing purposes I want to reload classes that have either static non-final fileds or static initialization blocks.

With static fields it is easy - I can check that class has it using reflection.

But how I can check that class has static block/blocks ? Don't want to operate with this blocks, just want to know are they here or not.





mardi 30 mai 2017

Microsoft Dependency Injection resolving generic type returns null

I am trying to translate something I used to do in Autofac to Microsoft Dependency Injection. I have a bunch of RequestHandlers that are based on an interface:

public interface IRequestHandler<TParameter, TResult>
    where TResult : IResponse
    where TParameter : IRequest
{
    TResult Handle(TParameter query);
}

I have registered all request handlers and all my IResponse objects and my IRequest objects by doing this:

 var requestHandlerAsyncs = ReflectionUtils.GetClosedTypes(typeof(IRequestHandlerAsync<,>), assemblies);
        foreach (var requestHandler in requestHandlerAsyncs)
        {
            serviceCollection.AddScoped(requestHandler);
        }

Im collecting all my types to be registered like this:

 public static IEnumerable<Type> GetClosedTypes(Type openGeneric, params Assembly[] assemblies)
    {
        if (assemblies == null || assemblies.Length == 0)
        {
            return new Type[0];
        }

        var list = new List<Type>();
        foreach (var assembly in assemblies)
        {
            if (!assembly.IsDynamic)
            {
                var types = ReflectionUtils.GetExportedTypes(assembly);

                var q = from type in types
                        from i in type.GetInterfaces()
                        where i.IsGenericType && i.GetGenericTypeDefinition() == openGeneric
                        select type;

                list.AddRange(q);
            }
        }

        return list;
    }

I can step through code and see that they are registered. I would then like to be able to retrieve them generically, by having a RequestDispatcher that retrieves the item from the ServideProvider and calls the Handle method:

 public TResult Dispatch<TParameter, TResult>(TParameter query)
        where TParameter : IRequest
        where TResult : IResponse
    {
        //Get the approproprite command handler by resolving it from the autofac _serviceProvider based on the IQuery and IQueryResult
        var handler = _serviceProvider.GetService<IRequestHandler<TParameter, TResult>>();
        return handler.Handle(query);
    }

But GetService returns null. I suspect it has something to do with the way items are registered in the container. Here is how I used to register things in Autofac:

builder.RegisterAssemblyTypes(MyAssembly)
            .AsClosedTypesOf(typeof(IRequestHandler<,>))
            .InstancePerLifetimeScope()
            .AsImplementedInterfaces();





Dynamically creating object based on type

I have the following code:

public async Task DispatchAsync(NoticeChannelType type, string message)
    {
        switch (type)
        {
            case NoticeChannelType.Email:
                {
                    var email = JsonConvert.DeserializeObject<NoticeEmail>(message);
                    await _channelResolver.ResolveAsync(email);
                }
                break;
            case NoticeChannelType.Pushover:
                {
                    var pushover = JsonConvert.DeserializeObject<NoticePushover>(message);
                    await _channelResolver.ResolveAsync(pushover);
                }
                break;
            default:
                break;
        }
    }

I would like to remove this switch somehow, create and cast the object to the concrete type.

After that the channelResolver.ResolveAsync is implemented as follows:

public async Task ResolveAsync<T>(T channel) where T : INoticeChannel
    {
        if (channel == null)
            throw new ArgumentNullException(nameof(channel),
                $"Channel: '{typeof(T).Name}' cannot be null.");

        var handler = _context.Resolve<INoticeExecutor<T>>();

        await handler.SendAsync(channel);
    }

I was trying to refactor it to something like this:

public async Task DispatchAsync(NoticeChannelType type, string message)
    {
        var channel = _context.ResolveKeyed<INoticeChannel>(type);

        Type myType = Type.GetType(channel.GetType().FullName);

        await _channelResolver.ResolveAsync((INoticeChannel)JsonConvert.DeserializeObject(message, myType));
    }

but after that in the channelResolver.ResolveAsync type T is INoticeChannel and not the concrete type so the _context.Resolve<INoticeExecutor<T>>(); can`t resolve it.

Is this possible to remove this switch and make this code more elegant and easier to maintain?





How to get the class type for which a collection object is created using reflection

I need your help to solve this, I have been trying to get an answer but didn't find one and I have very less time left to complete the assignment.

Code below :

 public class MainClass {
      @SuppressWarnings("unchecked")
      public static void main(String args[]) throws ClassNotFoundException {
           @SuppressWarnings("rawtypes")
           Class aClass = EmployeeDao.class;
           Method[] methods = aClass.getDeclaredMethods();

           @SuppressWarnings("rawtypes")
           Class returnType = null;
           for (Method method : methods) {
               if (!method.getReturnType().equals(Void.TYPE)) {
                  System.out.println(method.getName());

                  returnType = method.getReturnType();
                  if (returnType.isAssignableFrom(HashSet.class)) {
                      System.out.println("hash set");
                  }  
               }
           }
     }
 }

in the above code I am getting all the methods of a class and checking if its return type is HashSet and in that case I need to find out the type of object contained by the set object, for example the below method of EmployeeDao class:

public Set<Employee> findAllEmployees() {
     //some code here
}

I want to get the class object for Employee for the above method, I am not getting how to do it. The code above is static and I know in the above case, but this has to be done dynamically and above is only a demo code, at real time this program will get the class whose methods has to be accessed as an argument.





Set attribute of bean from a Generic Method Java

I am facing some difficulties to solve this problem. I have to make changes from a "generic" method for parsing CSV files to POJO lists. It was implemented by somebody else. The clazz parameters represent the possible beans that match the type of CSV file. I have to implement a certain logic for setting the last time a file was persisted in my database. Like this, I can keep track when was the last Parsed and persisted file and launch my batching process from this file for avoiding re-reading the whole folder. Should I use reflection or something like:

//  clazz.getMethod("setDate", initialDateFromFileName);

This is a little piece of the method where I already implemented the logic for retrieving the date I want following some business rules I have to stick with.

    private <T> List<T> performProcessing(String path, List<String> headers, Class<T> clazz, String pattern,
                String account, String fileSeparator){
  LOGGER.info("Start perform CSV Processing for account: " + account + " and pattern :" + pattern);

    List<T> listTargetObject = new ArrayList<>();
    Date lastModifiedDate = (Date) quartzDatabaseRepositoryIn.getLastModifiedDate(account);
    List<String> titleCase = new ArrayList<>();
    File folder = new File(path);
    File[] files = folder.listFiles();

    DateUtils.sortFilesByLastModifiedDateDescending(files);

    for (File file : files) {

        if (file.getName().contains(pattern)) {

            LOGGER.info(MessageFormat.format(FILE_RETRIEVED_LOGGER_MESSAGE, file.getName()));
            Date initialDateFromFileName = DateUtils.getDateFromFileName(file.getName());

            if (initialDateFromFileName.after(lastModifiedDate)) {


                  LOGIC FOR Unmarshalling
       ...
}

Then there is another method who will call the performCSV put it into an ArrayList of Foo Objects and persist into the database.

And let say I have a Bean(class) named: Class.java with different instance variables and one of them is

private Date date;
//With setters and getters

My question is: how could I access each setDate for each clazz parameter I will pass into this method?





How to check for an Attribute in a MemberInfo from inside another Attribute?

I implemented the Attribute MyValidate to validate requests to WebApi calls. It's been applied on class level and it's working as expected.

Now I need to make exceptions on some methods and I'm intending to create a new Attribute MyNoValidate. The idea is to change MyValidate to check if the method is also marked with MyNoValidate, thus skipping the validation logic itself, but I don't know how to do it.

public class MyValidate : Attribute
{
   private bool ignoreThisMethod = false;
   public MyValidate()
   {
     if(_the_target_method_has_MyNoValidate()) ignoreThisMethod = true;
   }
}

public class MyNoValidate : Attribute
{ /* nothing to implement */ }

[MyValidate]
public class WillBeValidated
{
   public void ThisMethodWillBeValidated_1() {...}
   public void ThisMethodWillBeValidated_2() {...}

   [MyNoValidate]
   public void ThisIsAnExpecialCasThatWillNotBeValidated() {...}
}





Getting inner class field values using reflection

I am trying to access inner class field values using reflection.

Suppose the classes are:-

public class OuterClass  {
    int a;
    public class InnerClass {
        int b;
        InnerClass(int b){
            this.b = b;
       }
    }

    public void setInnerField(int val){
        InnerClass a = new InnerClass(val);
    }
}

And the main function has:-

OuterClass obj = new OuterClass();
obj.a = 10;
obj.setInnerField(5);

Following is what I am trying to get the inner class field value i.e. b Referred from How i can access inner class variable value using reflection in java?

Class[] classes = obj.getClass().getDeclaredClasses();     
for(Class innerClass: classes){
    //System.out.println(innerClass.getName());
    Field[] fields = innerClass.getDeclaredFields();
    for(Field field : fields){
        //System.out.println(field.getName());
        System.out.println(field.get(obj));  //<-----IllegalArgumentException    
//Tried with below line too as suggested in above link                                                                     
System.out.println(field.get(innerClass.getInterfaces())); //<-----IllegalArgumentException
    }           
}

Then what can be the ways to access the inner class field values at runtime?





Goalng reflect SetString

I have a struct like this one:

type ProductionInfo struct {
    StructA []Entry
}

type Entry struct {
    Field1 string
    Field2 int
}

I would like to change the value of Field1 using reflection but the reflect object returned always CanSet() = false. What can I do? See playground example.

http://ift.tt/2ric19t





lundi 29 mai 2017

Adding new paths for native libraries at runtime in Java9

I have an app that includes some native code. In an effort to make things easy for users to install and run, I have been extending the private field ClassLoader.sys_paths at runtime as described in this previous question: Adding new paths for native libraries at runtime in Java. With this hack the app can run with a simple unadorned java -jar app.jar command and the native objects will be located correctly in the installation directory.

This technique no longer works in Java 9 (see How to solve InaccessibleObjectException ("Unable to make {member} accessible: module {A} does not 'opens {package}' to {B}") on Java 9?). This article describes the changes to Java 9 and suggests a solution (adding arguments to the command line to open the module), but this defeats my original intent of allowing a simple execution of the java command.

Is there any way to change the native library search path at runtime, or is this considered too much of a loaded gun to leave lying around?





Java generics - Type casting issue

I have a generic method which accepts class type and fields of that class to be updated. For ex:

class A {
  private int a;
  private int b;
}

class B {
 private int c;
 private int d;
}

At run time, if we pass class type as "A.class" and fieldstoBeUpdated as "b", what is the best way to access the field's getter/setter of that particular class, so that we can modify the fields.

public <T> void find(T clazz, List<String> fieldsToBeUpdated) {
            if (clazz instanceof A) {
                fieldsToBeUpdated.parallelStream().forEach(field -> {
                    switch(field) {
                    case "a":((A)p).setCreatedTime(TimeUtils.toGMT(((A)p).getCreatedTime(), ZoneOffset.of("+05:30")));
                    break;
                    case "b":((A)p).setUpdatedTime(TimeUtils.toGMT(((A)p).getUpdatedTime(), ZoneOffset.of("+05:30")));
                    break;
                    }
                });
            }

            if (clazz instanceof B) {
                fieldsToBeUpdated.parallelStream().forEach(field -> {
                    switch(field) {
                    case "c":((B)p).setCreatedTime(TimeUtils.toGMT(((B)p).getCreatedTime(), ZoneOffset.of("+05:30")));
                    break;
                    case "d":((B)p).setUpdatedTime(TimeUtils.toGMT(((B)p).getUpdatedTime(), ZoneOffset.of("+05:30")));
                    break;
                    }
                });
            }
}

I have written above code to achieve the same.

But the problem is that i have 30 such classes to be passed as a parameter to this generic method with list of fields of that class to update/modify.

Its not the correct implementation to write 30 such if statements checking for the class type and then type casting the object to that class.

Is there any better way to achieve the same ?

Thanks in advance.





Is there a way to Reflect JavaScript properties and method from a "class" or function, not from an object?

It's very easy to get reflection from a JavaScript object, just as following code.

var getAllMembers = function (obj) {
    var members = {};
    members.properties = [];
    members.methods = [];

    for (var prop in obj) {
        if (typeof obj[prop] != 'function')
            members.properties.push(prop);
        else members.methods.push(prop);
    }
    return members;
}

function demo_class(na, nb) {
    this.a = na;
    this.b = nb;

    this.funca = function () {
        console.log(this.a);
    }
    this.funcb = function () {
        console.log(this.b);
    }
}

var x = new demo_class(1234, 4321);

var members = getAllMembers(x);

console.log(members.properties);  // [ 'a', 'b' ]
console.log(members.methods);     // [ 'funca', 'funcb' ]

My question is: Is there a way to get properties and methods from a class or function, instead of from an object? For example, like this:

var members = getAllMembers(demo_class); // Only can get '[] []'





dimanche 28 mai 2017

Get internal constructor in UWP

How to get internal parametrized constructor in UWP.

Why there is no such overload in UWP?

var ctr = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, 
                                   null, CallingConventions.HasThis, 
                                   new[] {typeof(IBuffer)}, null);

The only overload i can call in UWP is this

var ctr = typeof(T).GetConstructor(new[]{typeof(IBuffer)});

Which only gets public constructors.





Why my typereference not work?

Here is my code.

First, I have two classes:

public abstract class AbstractTypeReference<T> {
    public Type type();
    public AbstractTypeReference() {
        Type superClass = getClass().getGenericSuperclass();
        type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
    }
}

public class MyTypeReference<T> extends AbstractTypeReference<T> {
    public MyTypeReference() {
        super();
    }
}

Then, I run following code:

MyTypeReference<String> ref = new MyTypeReference<String>();
System.out.println(ref.type.toString());

I expect to get java.lang.String as output, but get T instead. The code was copied from com.fasterxml.jackson.core.type. But it works well. Could anyone tell me what is wrong? And why?





How to print, scan, binary-write, and binary-read without writing (much) code

I hate writing configuration data classes for my c++ programs: dumb little data classes, with a few standard functions: print() and scan(), sometimes binary read() and write(), and typically a bind() that ties each data member to a boost::program_options::options_description (so I can set configuration data from command-line or config file).

I've made an initial attempt at using templates to reduce the monotony of writing these classes, and I was wondering if someone could tell me if I'm reinventing the wheel before I invest any more time. I'd also like to know if there's anyone at all who appreciates what I'm trying to do (as opposed to thinking me completely nuts.)

The basic idea is that instead of writing print(), scan(), read(), write(), etc, I inherit from Print, Scan, Read, and Write (which I'll call service classes for lack of a better name) which respectively implement for me (via double dispatch) the a fore mentioned methods, each going through the monotonous task of printing, scanning, reading or writing each data member in sequence. Surely, these inherited methods are slower in execution than one written by hand, but I don't really care if it takes a few more microseconds to print or scan configuration data. More importantly, none of these inherited classes add data (so there is no additional overhead for instantiating or copying instances of my config classes).

I have to do 3 things to a class to make it all work:

  1. Provide an implementation for the pure-virtual className() method.
  2. Inherit from the interface classes I want implemented for me.
  3. Depending on which interfaces I choose, I have to include one or two getter methods (one const, and one non-const) for each data member.

Then I also have to write a partial-template specialization of a "Class" class that describes my class. Finally, an instance of each such Class must be loaded to each service class (which use them to figure out how to process class instances).

Below is a main.cpp that hopefully gives you a feel for what I'm doing. Let me know what you think.

#include "Print.hpp"
#include "Scan.hpp"
#include "Write.hpp"
#include "Read.hpp"

using namespace std;

class MyConfig : public Print, public Scan, public Write, public Read {
    public:
        const string className() const { return "MyConfig"; }

        const int&    i() const     { return _i; }
        const string& s() const     { return _s; }

        void i(int value)           { _i = value; }
        void s(const string& value) { _s = value; }

    private:
        int    _i;
        string _s;

        // The Scan and Read interfaces require a way to write the set
        // directly, hence these getter methods that return non-const
        // references.  I make these private, then define the friend below
        // so Scan and Read can get at them.
        //
        int&    i() { return _i; }
        string& s() { return _s; }

        template<class C, class P> friend class Class;
};


// Meta-class describing the members of class MyConfig and
// how to get at them.
//
template<class P>
class Class<MyConfig,P> : public ClassImpl<MyConfig,P> {
    public:
        Class() : ClassImpl<MyConfig,P>("MyConfig") {
            *this->template genMember<int>   ("i", &MyConfig::i, &MyConfig::i);
            *this->template genMember<string>("s", &MyConfig::s, &MyConfig::s);
        }
};

int main(int argc, char** argv) {
    try {
        // Each interface class is loaded with Class objects describing
        // user-data classes that use the interface.
        //
        Print::addClass<MyConfig>();
        Scan ::addClass<MyConfig>();
        Write::addClass<MyConfig>();
        Read ::addClass<MyConfig>();

        MyConfig x;
        x.i(3);
        x.s("abc");

        cout << "Printing config:\n" << x; // print x
        cout << "Scanning config:" << endl;
        cin  >> x; // scan x
        cout << "The scanned config was:" << endl;
        cout << x; // print x again

        cout << "Writing config to file." << endl;
        ofstream ofs;
        ofs.exceptions(ios::failbit | ios::badbit);
        ofs.open("testfile", ios::out | ios::binary);
        x.write(ofs); // write x to file in binary format
        ofs.close();

        cout << "Reading config back from file." << endl;
        MyConfig x2;
        ifstream ifs;
        ifs.exceptions(ios::failbit | ios::badbit | ios::eofbit);
        ifs.open("testfile", ios::in | ios::binary);
        x2.read(ifs); // read x from file in binary format
        ifs.close();
        cout << x2;
    }
    catch(const exception& x) {
        cerr << argv[0] << ":  " << x.what() << endl;
        return 1;
    }
    return 0;
}

Program output:

matt@dworkin:$ ./a.out
Printing config:
i = 3
s = abc
Scanning config:
i=4
s=xyz
The scanned config was:
i = 4
s = xyz
Writing config to file.
Reading config back from file.
i = 4
s = xyz





samedi 27 mai 2017

Iterate over Java object methods with no args and non-void return type and print toString return value (for debugging)

I would like to dump content of complex Java objects for debugging purpose.

For example I want to dump of toString() from return value of all get...() methods of HttpServletRequest object.

I am not interested in fields but rather in methods return values.

I am not sure if it's possible with commons-beanutils or ReflectionToStringBuilder.toString()

Currently I implemented with Introspector core API:

public static String dump(Object obj, String regex) {
    StringBuilder sb = new StringBuilder();

    try {
        BeanInfo info = Introspector.getBeanInfo(obj.getClass());
        for (MethodDescriptor descr : info.getMethodDescriptors()) {
            String name = descr.getName();
            Method method = descr.getMethod();
            if ( ! name.matches(regex))
                continue;
            if (method.getParameterCount() > 0)
                continue;
            if (Stream.class.isAssignableFrom(method.getReturnType()))
                continue;
            Object objValue = method.invoke(obj);
            String strValue = Optional.ofNullable(objValue).map(Object::toString).orElse("null");
            logger.info("name: {}, value: {}", name, strValue);
            sb.append(name);
            sb.append(" => ");
            sb.append(strValue);
            sb.append("\n");
        }
    } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        ex.printStackTrace();
    }

    return sb.toString();
}

but I would like to use something standard and flexible...





How to know the members of a extended class in typescript

The following code let to know the names and the properties of the members of a class in typescript language:

export class Teacher 
{
   Id: number;
   Name: string;
}

var teacher = new Teacher();

for(p in teacher) 

{

 var typeField = null;

 switch (typeof (teacher[p])) 
 {

       case 'string':

         typeField = "String";
         break;

       case 'number':

         typeField = "Number";
         break;

       case 'object':

         typeField = "Date";
         break;

       case 'boolean':

         typeField = "Boolean";
         break;
      }

 .....
 .....
}

But if I extend the class in this way:

export class Person
{
   Id: number;
   FirstName: string;
   LastName: string;
}

export class Teacher extends Person
{
   Id: number;
   IdPerson: number;
   School: string
}

The previous code does not work correctly because it lists only some members but not all. Can someone propose me the solution to have the complete list of the members ? Thanks. M.P.





ignore CaseSensitive "method Name" for getting a method of a Class in java

i want to get a Method of a Class in this Way:

 int value = 5;
 Class paramType = value.getClass();
 String MethodName = "myMethod";
 Class<?> theClass = obj.getClass();
 Method m = theClass.getMethod(MethodName, paramType);

is it possible to ingore "MethodName" CaseSensitive? for example if there is a method in "theClass" with name "foO", How Can I find it with having MethodName="FOo"?





Golang reflect getting struct members in a slice

I've the following structure:

type ProductionInfo struct {
StructA []struct {
    Field1            string
    Field2            int
}

I would extract fields name and type from StructA in the ProductionInfo type. But I cannot understand how. Can anybody help me?





vendredi 26 mai 2017

Typescript Form Generation

I'm trying to write a compontent that generates a form based on the metadata of a typescript file. I'm having runtime object trouble determining the if a property is of a specific type.

export interface Email{
   value: string;
}

export interface User {
    id: number; 
    firstName: string;
    lastName: string;
    email: Email;
    birthday: Date;
 }

I would like to be able to know the property type /interface type at runtime so I can create the appropriate form elements.

properyLogger<T>(property: T) {
    //This cause a compiler error
    if (property instanceof Email) {
        console.log('Email');
    } else if (property instanceof Date) {
        console.log('Date');
    }
    else if (typeof property === "string") {
        console.log('string');
    } else if (typeof property === "number") {
        console.log('number');
    } 
}

How can I get Interface/Class information at runtime. Alternatively I would be willing to use decorator on the model if that would help. I need this solution to work on most modern browsers





Access to iOS SDK constant via name (reflection)

Inside of iOS SDK, lots of constants defined by Apple can be found looking something like this:

extern const CFStringRef kSomeReallyNiceConstant
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_8_0);

If I check for presence of this constant standard way:

if (NULL == &kSomeReallyNiceConstant)

I am pretty much referencing it and in order for my code to compile properly, I need at least iOS SDK 8.0 or higher in this case.

When it comes to objects and methods, reflection approach works nicely with usage of NSClassFromString, respondsToSelector and performSelector.

Is there a chance to use some kind of reflection (access to string constant by name) in attempt to get it's value if it exists (or none if it doesn't)?

I know that I can use macros to check for iOS version and execute different code paths based on that information, but I don't want to use that approach.

I managed to do this with pointer:

#include <dlfcn.h>

// ...

int *pointer = dlsym(RTLD_SELF, "kSomeReallyNiceConstant");

if (pointer) {
    NSLog(@"Thing exists!");
} else {
    NSLog(@"Nope, doesn't exist!");
}

but I am not sure if this is something that would cause app rejection. Do you maybe know?

Regardless of this pointer approach, I'm curious to hear if there's any other way to achieve this?





X is a variable but used like a type when trying to cast

I have the following code. I am passing a string of the name of the entity type I want to query and getting the type based on the string. I want to get the DbSet back and return an IQueryable. The problem is where I am doing (DbSet< tableEntity >) and getting the following error: ta"bleEntity is a variable but used like a type" when trying to cast. Is there a way to resolve this?

public object GetList(string tableEntity)
{
    Type tableEntity = Type.GetType("TestProject." + typeName
 + ", TestProject");

    var dbObject = (DbSet<tableEntity>)typeof(DbContext).GetMethod("Set", Type.EmptyTypes)
                        .MakeGenericMethod(tableEntity)
                        .Invoke(databaseContext, null);

    return dbObject.AsQueryable();            
}





Find attribute of specific type in nested objects

I often have to deal with DTOs that contains other DTOs and I'd like to scan one object's attributes (and their own attributes, recursively) and retrieve every accessible object of class Bingo in the whole hierarchy.

For example, when I have the following :

public static class Bingo {
    // the one I want to get
}

public static class Foo {
    private Bar bar;
    private Bingo bingo;
    private List<Bingo> bingos;

    // getters & setters
}

public static class Bar {

    private Bingo bingo;

    // getters & setters
}

I'd like to get all instances of Bingo found in attributes of my Foo object, including the ones in the Bar object and the List.

Is there a library conveniently doing that ?

A more complete test case (using a bit of JUnit) :

public static class Bingo {
    private final int id;

    public Bingo(int in_id) {
        id = in_id;
    }

    @Override
    public String toString() {
        return "Bingo#"+String.valueOf(id);
    }

}

public static class BingoWrapper {

    private Bingo bingo;

    public Bingo getBingo() {
        return bingo;
    }

    public void setBingo(Bingo in_bingo) {
        bingo = in_bingo;
    }
}

public static class BingoFactory {

    private final List<Bingo> ALL_BINGOS = new ArrayList<>();
    private int sequence = 0;

    public Bingo createBingo(){
        Bingo l_bingo = new Bingo(sequence++);
        ALL_BINGOS.add(l_bingo);
        return l_bingo;
    }

    public BingoWrapper createBingoWrapper(){
        BingoWrapper l_bar = new BingoWrapper();
        l_bar.setBingo(createBingo());
        return l_bar;
    }

    public List<Bingo> getAllBingos(){
        return ALL_BINGOS.stream().collect(Collectors.toList());
    }

}

public static class Foo {

    private Bingo bingo;
    private BingoWrapper wrapper;
    private Bingo[] array;
    private Collection<Object> collection;
    private Map<Object,Object> map;

    public Bingo getBingo() {
        return bingo;
    }
    public void setBingo(Bingo in_bingo) {
        bingo = in_bingo;
    }
    public BingoWrapper getWrapper() {
        return wrapper;
    }
    public void setWrapper(BingoWrapper in_bar) {
        wrapper = in_bar;
    }
    public Bingo[] getArray() {
        return array;
    }
    public void setArray(Bingo[] in_array) {
        array = in_array;
    }
    public Collection<Object> getCollection() {
        return collection;
    }
    public void setCollection(Collection<Object> in_collection) {
        collection = in_collection;
    }
    public Map<Object, Object> getMap() {
        return map;
    }
    public void setMap(Map<Object, Object> in_map) {
        map = in_map;
    }
}

@Test
public void test(){
    BingoFactory l_bingoFactory = new BingoFactory();

    Foo l_foo = new Foo();
    l_foo.setBingo(l_bingoFactory.createBingo());                  // one in a field
    l_foo.setWrapper(l_bingoFactory.createBingoWrapper());         // one in a field of a field

    l_foo.setArray(new Bingo[]{l_bingoFactory.createBingo()});     // one in an array in a field

    l_foo.setCollection(Arrays.asList(
            l_bingoFactory.createBingo(),                          // one in Collection in a field
            l_bingoFactory.createBingoWrapper()));                 // one in a field of an item in a Collection in a field

    Map<Object,Object> l_map = new HashMap<>();
    l_foo.setMap(l_map);
    l_map.put("key", l_bingoFactory.createBingo());                // one as a key in a Map in a field
    l_map.put(l_bingoFactory.createBingo(), "value");              // one as a value in a Map in a field
    l_map.put("keyAgain", l_bingoFactory.createBingoWrapper());    // one wrapped in a value in a Map in a Field 
    l_map.put(l_bingoFactory.createBingoWrapper(), "valueAgain");  // one wrapped in a key in a Map in a field 

    List<Bingo> l_found = BeanUtils.scanObjectForType(l_foo, Bingo.class);   // Magic happens here

    System.out.println(l_found);                                   // for debug
    Assert.assertTrue(l_found.containsAll(l_bingoFactory.getAllBingos())); // I want them ALL
}





How to show all dependencies are present if the source code compiles? (false negatives welcome)

Given a Java source folder I'd like to declare that all the code required to execute the program is contained in the source folder or instead declare the source folder "suspect" if this cannot be definitively shown. Simply compiling the folder is not enough because there could be some code like:

Class<?> clazz = Class.forName("Foo");
clazz.newInstance();

Where Foo.java is not present in the source folder. But what if I search the codebase and show Class.forName is never used. Is that sufficient to show all dependencies are present if the folder compiles? Or are there other reflective techniques I need to search for as well? I'm fine with just assuming a dependency is not present if code like

`Class.forName(SOME_MYSTERY_STRING_COMPUTED_AT_RUNTIME)` 

is found. I don't care about discovering if the argument to forName(...) is represented by the source folder or not. I'm fine with just assuming it is not and declaring the folder suspect. I'm also fine with similarly declaring the folder suspect if any set of reflective operations are used without having to deeply analyze them. I just need to know what that list of operations are in general.





Setting value of each parameter using Reflection

I would like to know how to set a value of parameter from method called using reflection ?

This an example below:

    ParameterInfo[] parameters = MethodBase.GetCurrentMethod().GetParameters();
    foreach (ParameterInfo parameter in parameters)
    {
        ..
       //set the value of parameter, looks like that "parameter.SetValue("myValue");
        ..
    }





Java - How to import 'Reflections' class?

Im trying to use reflections classes as suggested here http://ift.tt/2rp1FFF

Reflections reflections = new Reflections("my.project.prefix");
Set<Class<? extends SomeType>> subTypes = 
        reflections.getSubTypesOf(SomeType.class);
Set<SomeType> someTypes = new HashSet<SomeType>(subTypes.size());
for (Class<? extends SubType> subType : subTypes) {
    someTypes.add(subType.newInstance());
}

However, I cant seem to import the necessary package. NetBeans cant find it, and also I tried importing java.lang.reflections but it doesn't do it. I can see java.lang.Class, but I don't see Reflections class anywhere.

Can anyone please show me the way to the light?

t





How to use table-driven tests in Swift with class reflection

I have a lot of Realm data models that I want to test in a Quick spec. The mechanics of the test for each model is identical:

  1. Expect the realm to be empty for the object type
  2. Load sample data from a JSON file
  3. Init the model with the JSON data
  4. Save the model object to the realm
  5. Expect the realm to contain the loaded object

All the models inherit from the same BaseModel type.

Since the boilerplate code is the same I was hoping to use a table-driven approach to the tests using an array and class reflection like this:

let tests: [String] = [
    "Model1",
    "Model2",
    "Model3"
]
for testClass in tests {
    describe(testClass) {
        // Use reflection to get the model type, but really I don't want the base model type, I want the actual type since Realm needs it
        let modelType = NSClassFromString("MyApp.\(testClass)") as! BaseModel.Type
        // Test the model
        it("Adds good \(testClass) from json", closure: {
            expect(realm.objects(modelType).count).to(equal(0))

            if let json = self.loadJsonFromFile("event") {
                if let e = modelType.init(JSON: json) {
                    do {
                        try realm.write {
                            realm.add(e, update: true)
                        }
                    } catch {}
                }
            }

            expect(realm.objects(modelType).count).to(equal(1))

        })
    }
}

This fails because the BaseModel type isn't really want I want to instantiate. I want to instantiate the actual testClass type since I need to insert the correct model type into Realm for this to work. Also, the base model has several pieces undefined that Realm needs such as the primaryKey which is left to the descendent models to implement.

The concept of attempting to use reflection to get the actual model class is really separate from Realm so this isn't necessarily a Realm question. Since I don't know the model type in the loop except as the String value is there any way to get the actual model type rather than just the inherited parent type?





How to delegate a property by reflection in kotlin

for example

class A {
  val name:String? = "" 
}

now i want to delegate A's property to DelegateClass in main func:

fun main(args: Array<String>) {
A().javaclass.declaredFields....(how to do this)
}

thank u !





jeudi 25 mai 2017

Type.GetInterfaces() workaround for .NET Standard 1.x

.NET Core 1.1 supports Type.GetInterfaces() method which provides a list of the interfaces implemented on a given type. Unfortunately, Type.GetInterfaces() is not yet available in .NET Standard 1.x.

The good news is that it is supposed to included in .NET Standard 2.0.

In the meantime, does anyone know of a workaround I can use to get the list of interfaces on a type in .NET Standard 1.x?

Many thanks!





Iterating Through an Object of Anonymous Type to Retrieve Properties and Values

Working with Entity Framework (EF6) and VB.Net reflection, both of which I'm not super familiar with at this point.

Here's a brief example of what I'm trying to achieve:

Dim user as New user()
user.full_name = "John Smith"

Dim str As String = "The user's name is **full_name**."

'For each p As Property In user.Properties
'    str = str.Replace("**" + p.Name + "**", p.Value)
'Next

OUTPUT: The user's name is John Smith.

However, the catch is that the object is of an anonymous type. I'd like to be able to pass in any of my entity classes and dynamically replace property occurrences.

I've tried a whole lot and read a ton of questions here on SO, but I'm still having trouble - It's quite evident that I don't properly understand reflection just yet.

I'll supply my code below, as well as anything I've referenced. If anyone can push me in the right direction, I'd be more than grateful. Thanks.


System.Reflection.TargetParameterCountException: Parameter count mismatch.

Public Function MailMerge(htmlString As String, obj As Object)
    Dim keyNames As New List(Of String)

    Dim dictionaryData As New Dictionary(Of String, String)()
    For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
        If p.CanRead Then
            Dim columnName As String = p.Name

            'FAILS HERE - p.Name is "Item" at the failing iteration
            Dim columnValue = p.GetValue(obj, Nothing)

            dictionaryData.Add(columnName, columnValue)
        End If
    Next

    For Each key In dictionaryData.Keys
        htmlString = htmlString.Replace("**" + key + "**", dictionaryData(key))
    Next

    Return htmlString

End Function


References:





Load jar file with URLCLassLoader

I am trying to load a jar file as if it was run with "java -jar BungeeCord.jar", but I am trying to do this from within another jar. I can not use a process builder because I need get an instance of classes uses in the external jar file.

I have created this:

System.out.println("Loading jar: " + jar.toURI().toURL());

    child = new URLClassLoader(new URL[]{jar.toURI().toURL()}, BungeeServer.class.getClassLoader());

    Class<?> classToLoad = Class.forName("net.md_5.bungee.Bootstrap", true, child);
    final Method method = classToLoad.getDeclaredMethod("main", String[].class);

    new Thread(new Runnable(){

        public void run() {
            try {
                method.invoke(null, (Object) new String[]{});
            } catch (Exception e) {
                e.printStackTrace();
                BungeeControl.shutdown();
            }
        }

    }).start();

This starts up the jar file, but it gets the following error about a dozen times on start which don't occur if I start the same file normally:

java.lang.NoClassDefFoundError: net/md_5/bungee/api/plugin/Plugin
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at net.md_5.bungee.api.plugin.PluginClassloader.loadClass0(PluginClassloader.java:34)
    at net.md_5.bungee.api.plugin.PluginClassloader.loadClass(PluginClassloader.java:27)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at net.md_5.bungee.api.plugin.PluginManager.enablePlugin(PluginManager.java:304)
    at net.md_5.bungee.api.plugin.PluginManager.loadPlugins(PluginManager.java:212)
    at net.md_5.bungee.BungeeCord.start(BungeeCord.java:264)
    at net.md_5.bungee.BungeeCordLauncher.main(BungeeCordLauncher.java:55)
    at net.md_5.bungee.Bootstrap.main(Bootstrap.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.moltrespvp.bungeecontrol.BungeeServer$1.run(BungeeServer.java:31)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: net.md_5.bungee.api.plugin.Plugin
    at net.md_5.bungee.api.plugin.PluginClassloader.loadClass0(PluginClassloader.java:53)
    at net.md_5.bungee.api.plugin.PluginClassloader.loadClass(PluginClassloader.java:27)
    at java.lang.ClassLoader.loadClass(Unknown Source)

If needed, here is the manifest for Bungeecord:

Manifest-Version: 1.0
Implementation-Version: git:BungeeCord-Bootstrap:1.12-SNAPSHOT:16d2615
 :1233
Archiver-Version: Plexus Archiver
Built-By: jenkins
Created-By: Apache Maven 3.2.5
Build-Jdk: 1.8.0_121
Specification-Version: 20170514
Main-Class: net.md_5.bungee.Bootstrap

How can I start this jar file as if I started it with a ProcessBuilder, but be able to access methods from the running instance.

For example, I need to be able to run this for the running instance of BungeeCord ProxyServer.getInstance()?





How can we define a Genereic List just giving the textual class name?

I would like to know how to define a generic list just giving the textual class name and using System.Type as shown in the example below :

Type entity_type = Type.GetType("Entities.Human, Entities");

List<entity_type> a = new List<entity_type>();





Reflection : How to get the result (and do foreach on it) from method invoked using Reflection?

I would like to invoke some methods from different repository and having the same type "List<>" as result but I don't know how to cast the result without hard code and also how to use "foreach" on this result, here the example below :

class Person
{
    public string Name { get; set; }
}

class Animal
{
    public string Name { get; set; }
}

class PersonRepository
{
    public List<Person> GetPersons()
    {
          List<Person> list = new List<Person>();

          //Some processing...

          return list;
    }
}

class AnimalRepository
{
    public List<Animal> GetAnimals()
    {
        List<Animal> list = new List<Animal>();

        //Some processing...

         return list;
    }
}

public class ReflectionClass
{
    public List<T> GetResultFromMethodInvoked<T>(string entityName, string repositoryName, string methodName)
    {
        List<T> lists = new List<T>();
        Type entity_type = Type.GetType("Entities." + entityName + " ,Entities");
        Type repository = Type.GetType("Crud." + repositoryName + ", Crud");
        MethodInfo method = repository.GetType().GetMethod(methodName);


        var r= method.Invoke(repository, parameters);


        Convert.ChangeType(r, typeof(List<>).MakeGenericType(new Type[] { entity_type }));

        lists = (List<T>)r;

        return lists;
    }
}

class Program
{
    static void Main(string[] args)
    {
        ReflectionClass reflection = new ReflectionClass();
        /* Should have List<Person> as RESULT */
        reflection.GetResultFromMethodInvoked("Person", "PersonRepository", "GetPersons");

        /* Should have List<Animal> as RESULT */
        reflection.GetResultFromMethodInvoked("Animal", "AnimalRepository", "GetAnimals");
    }
}





How to determine which method called a method in java? [duplicate]

This question already has an answer here:

Suppose I have below code snippet:

class A{
 // Something made below line to execute
 new B().foo();
}

class B{
void foo(){
  new C().bar();
    }
}

class C{
void bar(){
// Log name 'foo' as foo method called bar
    }
}

How can I log method name in bar using some APIs to determine the caller method?





mercredi 24 mai 2017

Why Java Singleton needs to prevent the reflection attack

Effective Java 2nd describes the Enum Implementation as the best practice to implement a Singleton in Java.

But the advantage of that implementation against the Static Holder Implementation is that the enum can prevent the reflection attack.

So, there comes the question: Why do we need to prevent the reflection attack of singleton?

The other implementations of Java Singleton are just resolving the issues of multiple threads and lazy initialization.

These problems will and often appear at the daily development, but the reflection attack seems more like a Security Issue.

If the attacker can hack and crack your program, he and she could do whatever he and she wants, it seems it is no need to break the Singleton.





C# Invoking Exception TargetSite

I have an application that can sometimes throw an exception, most of these are handled but I want the unhandled ones to be recoverable. So I'm trying to invoke the method that caused the exception by using the exception's targetsite like so:

        Exception ex = Global.ThrownException;

        MethodBase mB = ex.TargetSite;


        try
        {

            mB.Invoke(mB, null);
        }
        catch(Exception exc)
        {
            System.Windows.MessageBox.Show(exc.Message);
        }

I'm doing this to make sure that the exception was a one time error before showing the window to the user again.

The test method (and the exception targetsite) I'm trying to invoke is this:

 public void testMethod()
    {
        throw new System.IO.IOException("test");
    }

When I run this, an exception is thrown with the message "Object does not match target type" but since testMethod doesn't have any parameters this shouldn't happen.

Any ideas?





Use reflection API to get field names and values

I'm creating a number of POJOs and have to create toString() methods for each. Instead of hand-coding each, I thought it would be easier to create a class to do the work for me using the reflection API -- create the functionality in one place and use it in each POJO.

All fields in the POJOs are private. The POJOs are Java object representations of JSON objects.

The requirements are to traverse the fields in a class, and list the fields along with the values.

I'm currently testing the functionality on a class called ChannelResource.

Here is the class that I'm using to list field names and values:

    import java.lang.reflect.Field;
    public class ToStringMaker {
      public ToStringMaker( Object o) {

      Class<? extends Object> c = o.getClass();
      Field[] fields = c.getDeclaredFields();
      for (Field field : fields) {
          String name = field.getName();            
          try {
            System.out.format("%n%s: %s", name, field.get(o));
          } catch (IllegalArgumentException e) {
            e.printStackTrace();
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }
      }
  }}

I'm passing an instance of the ChannelResource class to the constructor.

The compiler does not like field.get(o) in this line:

    System.out.format("%n%s: %s", name, field.get(o));

The compiler says:

    java.lang.IllegalAccessException: Class ToStringMaker can not access a member of class ChannelResource with modifiers "private"

ToStringMaker works if I make all members public, but I'd really rather not do that. Is there another way to get the value of a private field?

I know that the Apache organization has something that creates the toString functionality, but I don't like the format.





Instantiate a List

I would like to know if there is the possibility to instantiate a list of instances from textual class name. For example, I have this code below :

List<Person> Persons;

I would like to have this kind of control on specifiying class name for some objects:

string ClassName = "Person";
List<ClassName> Persons;

If there is some possibility using reflection, please help me, thank you.





How to get all fields of a class

I have two classes with same number of fields and with same field names . the only different is their field Types.

what I need too do is to get all fields value from one class and put them into the other one .

public class PersonA {
    private String name;
    private String family;
    //here AddressDto package is com.test.project.employer
    private AddressDto addressDto;
    //here ContactInfo package is com.test.project.employer
    private List<ContactInfo> contactInfo;
}

public class PersonB {
        private String name;
        private String family;
        //here AddressDto package is com.test.project.customer
        private AddressDto addressDto; 
        //here ContactInfo package is com.test.project.customer
        private List<ContactInfo> contactInfo;
    }

there might be other Dtos inside outer Dtos too or Maps with Custom Dtos , so I need to manage all fields to be checked if there is an other dto inside or not !

what I have done already , works for Java classes and Primitive types like String , BigDecimal , int and ... but not for my application dtos .

here is my code :

PersonA personA = new PersonA();
PersonB personB = new PersonB();

Field[] aFields = personA.getClass().getDeclaredFields();

for (Field field : aFields){
    field.setAccessible(true);
    Field bField= personB.getClass().getDeclaredField(field.getName());
    httpField.setAccessible(true);
    Object value = field.get(personA);
    bField.set(personB, value);
}

what I am thinking of is to write it in recursive form. Is there any solution for my problem ?





How can I force a ReflectionTypeLoadException? (C#)

I am trying to test an assembly extension method which is basically a wrapper around Assembly.GetTypes() which handles cases when a ReflectionTypeLoadException is thrown because for whatever reason one or more Types in the loaded Assembly could not be loaded.

I have tried explicitly throwing TypeLoadExceptions from the static & instance constructors, and also trying to instantiate an instance of this dummy class and calling the DoStuff() method to break it before trying to load the types, but Assembly.GetTypes() is always returning the Type and not throwing an ReflectionTypeLoadException.

How can I force this behaviour?

    public class WillNotInitiliase
    {
        public WillNotInitiliase()
        {
            BreakType();
        }

       static WillNotInitiliase()
       {
           BreakType();
       }

       public static  void DoStuff()
       {
       }

       private static void BreakType() => throw new TypeLoadException( "I can never be loaded" );
    }





Kotlin class generation

How can I create KClass in runtime in Kotlin? Is it possible or not? If it is possible - please, write small example with code as this:

class Example

Thank you!





mardi 23 mai 2017

Java reflection with a java Process

I have a Process which is a Java application which was created from ProcessBuilder by running a command like java -Xms1024M -jar my.jar. This works fantastically, but the application I started does not use System.in for its input, so I can NOT use process.getOutputStream().

How could I get an instance of the running application from the process to use Java Reflection to send input? If I can't, how would I go about using Java Reflection to start the application from my runnable, then use Java reflection to get something I can work with.

To be more specific, I am trying to do this for BungeeCord.

  • The main class is net.md_5.bungee.Bootstrap.
  • Bootstrap calls the static method main in net.md_5.bungee.BungeeCordLauncher.
  • BungeeCordLauncher creates an instance of net.md_5.bungee and puts this instance in a static field called instance in net.md_5.bungee.api.ProxyServer AND there is a get method (Maybe this could be used for java reflection?)
  • Inside BungeeCord.class there is a method called getConsoleReader() and this is what I ultimately need to get and I need the current instance of it for this specific process.

Thank you for any help!





Invoking generic extension method with parameters

Consider the following extension method:

public static class ValiDoc
{
        public static IEnumerable<RuleDescription> GetRules<T>(this AbstractValidator<T> validator, bool documentNested = false)
        {
             //....
        }
}

An implementation of AbstractValidator:

public class AddressValidator : AbstractValidator<Address>
{
    public AddressValidator()
    {
        RuleFor(address => address.HouseNumber).NotEmpty();
        RuleFor(address => address.StreetName).NotEmpty();
        RuleFor(address => address.PostCode).NotEmpty();
    }
}

I want to invoke the GetRules() extension method on ValiDoc via reflection and pass in an instance of AddressValidator as the first parameter, with a boolean for the second.

Having never played with Reflection before I am pretty overwhelmed, however by following the examples available here I have made some progress.

//Parameter 1
Type type = typeof(AbstractValidator<>);

// Instance of Address
Type constructed = type.MakeGenericType(childValidator.ValidatorType.GetTypeInfo().BaseType.GenericTypeArguments[0]);

// Find the extension method based on the signature I have defined for the usage
// public static IEnumerable<RuleDescription> GetRules<T>(this AbstractValidator<T> validator, bool documentNested = false)
var runtimeMethods = typeof(ValiDoc).GetRuntimeMethods();

MethodInfo generatedGetRules = null;

// Nothing fancy for now, just pick the first option as we know it is GetRules
using (IEnumerator<MethodInfo> enumer = runtimeMethods.GetEnumerator())
{
    if (enumer.MoveNext()) generatedGetRules = enumer.Current;
}

// Create the generic method instance of GetRules()
generatedGetRules = generatedGetRules.MakeGenericMethod(constructed);

//Parameter 1 = Derived from AbstractValidator<T>, Parameter 2 = boolean
var parameterArray = new object[] { childValidator.GetValidator(new PropertyValidatorContext(new ValidationContext(rule.Member.DeclaringType), rule, propertyName)), true };

//Invoke extension method with validator instance
generatedGetRules.Invoke(null, parameterArray);

When executing generatedGetRules.Invoke, I receive the following error message:

'Object of type 'ValiDoc.Tests.TestData.Validators.AddressValidator' cannot be converted to type 'FluentValidation.AbstractValidator1[FluentValidation.AbstractValidator1[ValiDoc.Tests.TestData.POCOs.Address]]'.'

Have I missed anything obvious? I can't tell if I am nearly there or miles away.

Supporting values:

typeof(AbstractValidator<>) = {FluentValidation.AbstractValidator`1[T]}

childValidator.ValidatorType.GetTypeInfo().BaseType.GenericTypeArguments[0] = {ValiDoc.Tests.TestData.POCOs.Address}

constructed = {FluentValidation.AbstractValidator`1[ValiDoc.Tests.TestData.POCOs.Address]}

generatedGetRules = {System.Collections.Generic.IEnumerable1[ValiDoc.Output.RuleDescription] GetRules[AbstractValidator1](FluentValidation.AbstractValidator1[FluentValidation.AbstractValidator1[ValiDoc.Tests.TestData.POCOs.Address]], Boolean)}

Parameter array = {ValiDoc.Tests.TestData.Validators.AddressValidator}, boolean





How to create class from string, register and then resolve using unity

I'm using C#, WPF, Prism 6.3 and using Unity as an IoC container.

Here's one part I don't quite understand and could use some clarity.

Scenario: My application will talk to multiple physical lasers. I created a LaserModule with Views/Viewmodels, as well as ILaser interface, and 3+ brand-specific laser classes (LaserA/B/C). Since all the Lasers have the same functionality (Connect, GetReading, Disconnect) I thought it was a good idea to make the ILaser interface so they all must implement these methods, but in whatever way they need to.

Furthermore, the module will read from a laser.cfg file and in that file it will have the settings for each laser, including the "Class" of the laser which I will use to instantiate the proper laser class with.

The overall idea is that the LaserModule will create however many lasers are in the config file, of the appropriate type, and then register them in a unity container so they can be access throughout other parts of the application. In the other parts of my application, the goal is that the programmer shouldn't need to know anything about the particular laser or specific class, instead just work using the interface. The interfaces will all be stored in a common module, so that should be the only dependency.

This is where I'm at now... and it appears to be working because when the .Greet() methods are called at the end, I see the greeting that I gave when using Activator.CreateInstance.

Is this approach realistic or am I totally missing the point?

namespace LaserModule
{
    interface ILaser
    {
        void Greet();
    }
}


namespace LaserModule
{
    class LaserA: ILaser
    {

        private string greeting = "blank";

        public LaserA(string greet)
        {
            this.greeting = greet;
        }

        public void Greet()
        {
            MessageBox.Show("LaserA - " + greeting);
        }
    }
}

public void Initialize()
{

    //Create Laser objects based on what brand of laser is supplied
    String className = ReadLaserClassNameFunc1();
    Type t = Type.GetType("LaserModule." + className, true);
    object t2 = (Activator.CreateInstance(t,"laser 1 greeting"));
    ILaser myLaser1 = (ILaser)t2;

    //Create Laser objects based on what brand of laser is supplied
    className = ReadLaserClassNameFunc2();
    t = Type.GetType("LaserModule." + className, true);
    object t2 = (Activator.CreateInstance(t,"laser 2 greeting"));
    ILaser myLaser2 = (ILaser)t2;

    //Create Laser objects based on what brand of laser is supplied
    className = ReadLaserClassNameFunc3();
    t = Type.GetType("LaserModule." + className, true);
    object t2 = (Activator.CreateInstance(t,"laser 3 greeting"));
    ILaser myLaser3 = (ILaser)t2;


    _unityContainer.RegisterInstance("Laser1", myLaser1, new ContainerControlledLifetimeManager());
    _unityContainer.RegisterInstance("Laser2", myLaser2, new ContainerControlledLifetimeManager());
    _unityContainer.RegisterInstance("Laser3", myLaser3, new ContainerControlledLifetimeManager());

    ...
    //The following lines would in reality be called from a different assembly.

    ILaser theLaser1 = _unityContainer.Resolve<ILaser>("Laser1");
    ILaser theLaser2 = _unityContainer.Resolve<ILaser>("Laser2");
    ILaser theLaser3 = _unityContainer.Resolve<ILaser>("Laser3");

    theLaser1.Greet();
    theLaser2.Greet();
    theLaser3.Greet();

}





How to get correct caller type inside the inherited static method in C#

Look at this code:

public class A
{
    public static void Foo() 
    {
       // How to get typeof(B) here if Foo called by using class B? 
    }
}

public class B : A
{
}

...

static class Program
{
    static void Main()
    {
        B.Foo();
    }
}

Here I have two non-static classes, but I have one static method inside the parent class. My question is how to get the type of class which used to call this static method inside this method? I can't use keyword this, because I do not create any objects here. I have tried already: MethodBase.GetCurrentMethod().DeclaringType and MethodBase.GetCurrentMethod().ReflectedType, but they both return me the typeof(A), but I need to get the typeof(B).





lundi 22 mai 2017

Correct approach to using MethodHandleProxies

In a Java project I'm currently working on, I'm dynamically loading classes then using the reflection API to find and execute methods of those classes that have certain annotations.

The code that performs the actual execution works exclusively in terms of Java-8 functional interfaces (for compatibility reasons), so I need to have an intermediate stage where the Method instances discovered using reflection are converted to appropriate functional interfaces. I achieve this using the MethodHandleProxies class.

For compatibility reasons again, the functional interfaces in question are generic interfaces. This causes an "unchecked conversion" warning when using the MethodHandleProxies.asInterfaceInstance method, since that method returns the "bare" interface.

The following is a brief example that reproduces the main steps involved:

import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.util.Arrays;

public class TestClass {
    private String prefix;

    public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, SecurityException {
        // Use reflection to find method.
        Method method = Arrays.stream(TestClass.class.getDeclaredMethods()) // Stream over methods of ConsumerClass
                .filter(m -> m.isAnnotationPresent(Marker.class)) // Retain only methods with @Marker annotation
                .findFirst().get(); // Get first such method (there is only one in this case)

        // Convert method to "MethodInterface" functional interface.
        MethodHandle handle = MethodHandles.lookup().unreflect(method);
        MethodInterface<TestClass, String> iface = MethodHandleProxies.asInterfaceInstance(MethodInterface.class, handle);

        // Call "testMethod" via functional interface.
        iface.call(new TestClass("A"), "B");
    }

    public TestClass(String prefix) {
        this.prefix = prefix;
    }

    @Marker
    public void testMethod(String arg) {
        System.out.println(prefix + " " + arg);
    }

    @Retention(RUNTIME)
    public @interface Marker { }

    @FunctionalInterface
    public interface MethodInterface<I,V> {
        void call(I instance, V value);
    }
}

This code compiles and runs, but has an unchecked conversion warning on the assignment to iface.

As I see it, I have three options:

  1. Simply live with the warning.
  2. Add an @SuppressWarnings annotation to the assignment.
  3. Come up with an alternative type-safe approach.

I try to ensure there are no warnings generated by my code (to minimise the opportunities for bugs), so I'm not keen on option 1. Option 2 feels like it's simply "papering over the cracks", but is acceptable if absolutely necessary. So my preferred option is to come up with a different approach.

Is there a different approach that is inherently type-safe?





How do I convince UnmarshalJSON to work with a slice subtype?

I want byte slices that marshal and unmarshal in JSON using base64 RawURLEncoding instead of StdEncoding. There's no obvious way to do this through the encoding/json package, which is sensible, so I thought I'd create a subtype to do it.

type Thing []byte

Marshaling support is easy:

func (thing Thing) MarshalJSON() ([]byte, error) {
    if thing == nil {
        return []byte("null"), nil
    }
    return []byte(`"` + base64.RawURLEncoding.EncodeToString(thing) + `"`), nil
}

But Unmarshal not so much. I traced the encoding/json source, and came up with:

func (thing Thing) UnmarshalJSON(data []byte) error {
    v := reflect.ValueOf(&thing)
    if len(data) == 0 || data[0] == 'n' { // null
        v.SetBytes([]byte{})
        return nil
    }
    data = data[1 : len(data)-1]
    dst := make([]byte, base64.RawURLEncoding.DecodedLen(len(data)))
    n, err := base64.RawURLEncoding.Decode(dst, data)
    if err != nil {
        return err
    }
    v.SetBytes(Thing(dst[:n]))
    return nil
}

But yields a panic in the call to SetBytes():

panic: reflect: reflect.Value.SetBytes using unaddressable value [recovered]
    panic: reflect: reflect.Value.SetBytes using unaddressable value

I tried using a pointer to a slice, instead, which works (and doesn't require reflection), but causes other challenges elsewhere in my code that wants to work with slices instead of pointers.

So two questions, I guess:

  1. Is this the best way to go about getting byte slices to marshal using RawURLEncoding?
  2. If so, how can I convince my byte slice subtype to reference the data decoded from the RawURLEncoding format?




How to determine all runtime (but not static) dependencies of Java source by reading the code?

Let's say I wanted to assert that a given Java source folder contained all of the source code required to run any of the programs contained in the source folder. Simply showing that the whole source folder compiles would be insufficient because perhaps some of those programs use reflection to instantiate objects. As such I could search through all the code and look for invocations of newInstance() to learn what classes are expected to be present at runtime. But what about calls to Class.forName(...) that are not involved in calls to newInstance() ? Better check for those as well. But how many such things do I need to check for?

Is there any sort of exhaustive list I could consult to ensure that I am considering each way in Java that such a runtime dependency could be introduced? Restated, does there exist some list of operations such that if I can show none of the source in a source folder use those operations (and that folder compiles) that all (code) dependencies are present?

If no such list exists, could we start one in this thread and make a best effort to cover all operations that we know of?





Unit tests with Mockito, spy and reflection on a Map object

I have a slightly complicated situation, and not sure how to handle it. There is an object with a private variable map (the object has already been initialized). This class has a series of operations on the map.

I need to write a unit test. It would get the private variable, mock(or spy) it, perform some operations on it, and verify the order of operations. What is the best way?

public class A{
   private Map<String, String> map = new Map()<>;

   }
   public method method1(){
     map.put("a", "A");
   }       

   public method method2(){ 
     if(map.size() > 0){
        map.put("b", "B");
     }

}
...
public class UnitTester{
@Test
public void test(){
    A ainstance = new A();
    Map<String,String> mock = mock(Map.class); //OR Map<String,String> mock = spy(Map.class); 

    Field f= A.class.getDeclaredField("map");
    f.setAccessible(true);
    f.set(ainstance, mock);

    ainstance.method1();
    ainstance.method2();

    InOrder inOrder = inOrder(mock);
    inOrder.verify(mock, times(2), put(anyString(), anyString()));  //Does not work

    }
}

map.put does not add anything into the map. Not sure if this is because it is a reflection object or what it is.





C# - How can I convert an object to a certain type

I'm trying to convert an object to a certain type and I don't know what that type actually is. I know it's either a primitive type or a string but not much else. And I don't wanna fill my code with a bunch of if's just checking the type. Here's the code

private object  MakeNewArray<TTDest>(object src, PropertyInfo getter) {
        object [] obj = (object[]) getter.GetValue(src);

        TTDest [] ret = new TTDest[obj.Length];
        for (int i = 0; i < obj.Length; i++) {
            ret[i] = (TTDest) obj[i];
        }
        return ret;
    }

And here's the part in the code where I call this method

Type tDest = destType.GetProperty(info.GetDest().Name)?.
PropertyInfo getter = info.GetSrc() as PropertyInfo;
Type elementType = tDest.GetElementType();
return MakeNewArray<elementType>(src, getter);





Receive annotation value from annotated field

Is it possible to receive annotation value inside a field, that was annotated? Imagine that I have this interface:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value();
}

And I have such implementation:

class SomeClass {
    @MyAnnotation("Annotation")
    private MyClass myClass;
}

What I want to understand is: is it possible to receive value of MyAnnotation inside MyClass? I want to implement a method inside class MyClass, which will return a value of assigned annotation. So, that myClass.getAssignedAnnotationValue() will return "Annotation". If it is not possible, please inform me.





Why does Java claim there's 2 declared methods when bounded generics are involved?

With the following definitions:

public interface BaseService<T, ID> {

    T findOne(@GraphQLArgument(name = "id") ID id);

}

public class BaseServiceImpl<T,ID extends Serializable> implements BaseService<T, ID> {

    @Override
    public T findOne(@GraphQLArgument(name = "id") ID id) {
        return null;
    }

}

Why does BaseServiceImpl.class.getDeclaredMethods() return 2 methods:

  • public java.lang.Object BaseServiceImpl.findOne(java.io.Serializable)
  • public java.lang.Object BaseServiceImpl.findOne(java.lang.Object)

Is there a way to filter these out?





GetConstructors vs. _baseType.GetMethod("GetConstructorImpl", BindingFlags.NonPublic | BindingFlags.Instance)

Is there a difference in c# / .net 4.5.1 between TYPE.GetConstructor(...) and TYPE.GetMethod("GetConstructorImpl", ...)?

I've always used the first solution and seen the second one in an external library.

Thanks a lot





Javascript Reflection: Determine if Single or Double Quoted String used to create object

I come from c# world, and there you can determine almost anything about any piece of code.

Because javascript has 2 syntaxes for defining strings 'single' and "double", i was curious if it is possible to determine which was used to create a particular string in an object. Anyone know how/if this can be done?

I'm just messing around, trying to "rebuild" a src file from an object, and got stuck on this particular point.

I've tried JSON.stringify(object) but that seems to give inconsistent results..





Use MEF to gather items to register in my Ioc container

I'm using.Net 4.6.2 with Microsoft DI. I want to register all items that implement a specific interface in my IOC. I was thinking of using MEF to gather all the items that implement an interface, loop through them and add them to my IOC. My concern is that this is sort of a waste of effort, or double effort, sort of registering things twice. Should I really just use reflection to scan an assembly for every item that implements my interface and registering it that way? My thought was that using MEF would make things easier to maintain, ensuring any new items would automatically get registered.





Kotlin reflection - creating objects from CSV

I have a data class named Member:

data class Member(){
    val first_name: String
    val last_name: String
    //30 more

    //a few simple methods
}

I am trying to import a CSV file. Each line of the file contains the fields I want to use to instantiate my Members.

fun ReadCsvFileKotlin() {
    val csvFile = "C:\\Data.csv"
    var memberList = mutableListOf<Member>()
    var reader = File(csvFile).readLines()
    var mbr: Member
    class Member(val p: Int)
    val prop = Member::p
    for(line in reader){
        val mbrProperties = line.split(",")
        for(i in 0..mbrProperties.lastIndex){
            //assign mbrProperties[i] to mbr property
            //mbrProperties[0] = "Bob"
            //mbr.first_name = "Bob"
            //Member::p = mbrProperties[i]
    }
    memberList.add(mbr)
}

I've done my research, but I'm failing to wrap my head around the information I've read and just can't bridge the gap between where I am and where I want to be.

Any advice would be appreciated! Walking me through or giving me examples using my example code would be welcome.

Background: I am automating tests for a website. Prior to executing each test, the member meeting the necessary test criteria is selected from a list, populated from the CSV file. I am looking to create my member objects in this fashion to reduce maintenance overhead as the test scope expands and additional criteria (and Member class fields) are added.

Why am I doing any of this in the manner I am doing? Because I still have much to learn... (So, if you see a better way, please, educate me!)

Thanks!





Can we get function argument/parameter values using Go

I already know how to get function name and function location:

func Trace(str string) string {
    pc := make([]uintptr, 10)  // at least 1 entry needed
    runtime.Callers(2, pc)
    f := runtime.FuncForPC(pc[0])
    file, line := f.FileLine(pc[0])
    str = Replace(str, "\n", ` `)
    return `-- ` + fmt.Sprintf("%s:%d %s:%s", file, line, f.Name() + str)
}

But how to get function argument values? For example, if I call that Trace function within:

func Test(a string, b int) {
  Trace(`demo`)
}
func main() {
  Trace(`aaaa`,123)
}

I want to get the value aaaa and 123 inside Trace function, without have to pass them manually to Trace function





Copy values of an object of one type to an object of another using C# reflection

I have been tasked with writing a routine against an existing database. This database has several tables that have identical structures, but different names (I did not design this, please do not suggest database design change). I am writing this in EF, and the models were created database-first.

The best option I can think of for this situation is to create a class that has the exact same properties, and create a routine that can accept generic types to copy data from the EF model to the generic model.

My models:

    // Sample EF database-first created model
    namespace SampleDataModel.Models
    {
        using System;
        using System.Collections.Generic;

        public partial class SampleClassFlavorOne
        {
            public int Id {get; set;}
            public string PropertyOne {get; set;}
            public string Property2 {get; set;}
            public DateTime Property3 {get; set;}
        }
    }

    // Sample of generic class I created
    public class GenericSampleClass{
        public int Id {get; set;}
        public string PropertyOne {get; set;}
        public string Property2 {get; set;}
        public DateTime Property3 {get; set;}
    }

My routine:

        private static void CopyFlavorToGenericList<T1, T2>(List<T1> fromList, List<T2> toList){
        foreach (var t in fromList)
        {
            //(As you can see, I have tried entering the foreach loop a both ways
            //foreach (var p in typeof(T1).GetProperties())

            foreach (var p in typeof(T2).GetProperties())
            {
                if (p != null && p.CanWrite)
                {
                    dynamic newObject = null;
                    p.SetValue((T2)newObject, p.GetValue(t, null), null);
                }
            }

            toList.Add(toObject);
        }
    }

Implementing the routine:

switch (flavor){
        case "FlavorOne":
            List<SampleClassFlavorOne> _baseFlavor = db.SampleClassFlavorOne.ToList();
            List<GenericSampleClass> _genericFlavor = new List<GenericSampleClass>();

            CopyFlavorToGenericList<SampleClassFlavorOne, GenericSampleClass>(_baseFlavor, _genericFlavor);
            break;
    }

No matter what I try, I always get:

An exception of type 'System.Reflection.TargetException' occurred in mscorlib.dll but was not handled in user code. Additional information: Object does not match target type.

I cannot figure out what I am missing.

  1. What may I be missing?
  2. Am I going about this the wrong way? If so, what is the correct way to do what I want to do given these conditions?

Any help appreciated, thanks!





Loading of imported classes of loaded classes using Reflection in Java

I am trying to load classes from a jar file. Basically, I want to call a method in a particular class in a package of that jar. The problem I am facing here is that after the class is successfully loaded from the jar and when I try to instantiate I get exception : ClassNotFound for classes imported in my class.

Here is the class which loads the class:

inputs: D:\Myjar.jar , com.vendor.epbroker.VNFLCMCommunicator

public Class<?> loadClass(String libPath, String pkgName) {
        LogManager.getLogger().info("Adding Class");

        File jarFile = null;
        try {
            jarFile = new File(libPath);
            URL fileURL = jarFile.toURI().toURL();
            String jarURL = "jar:" + fileURL + "!/";
            URL urls[] = { new URL(jarURL) };
            URLClassLoader ucl = new URLClassLoader(urls);
            Class<?> beanClass = ucl.loadClass(pkgName);
            ucl.close();

            return beanClass;
        } catch (Exception ex) {
            LogManager.getLogger().error("Given Library: " + libPath + " or Class name: " + pkgName + " is not Valid");
            LogManager.getLogger().error("Exception occurred : ", ex);
        }

        LogManager.getLogger().error("Class loading Error: Returning NULL");
        return null;
    }

The code snippet which receives this Class:

Object instance = classToLoad.newInstance();

                // To get the list of methods exist in the Class
Method[] listOfMethods = classToLoad.getMethods();

The following error is encountered:

SEVERE: Servlet.service() for servlet [spring] in context with path [/vnflcm] threw exception [Handler processing failed; nested exception is java.lang.NoClassDefFoundError: com/vendor/epbroker/exception/EPBrokerException] with root cause
java.lang.ClassNotFoundException: com.vendor.epbroker.exception.EPBrokerException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
    at java.lang.Class.getConstructor0(Class.java:3075)

Any help would be appreciated?





How do I grab the Property name and compared value from an expression?

We use filters at work which are a type

Expression < Func < T, bool > >

which we use with methods like:

Tuple< string, string, object > SplitFilter< People >(x => x.SurName == "Smith");

I need to make a method that takes a Expression< Func < T, bool > > as a parameter, like shown above, and breaks it down into 3 values, a string "SurName" for the property, a string "==" to represent an equality comparison, and a string "Smith" for the value being compared too.

I managed to get the string "SurName" out of it, but I can't for the life of my figure out how to determine the type of comparison (equality) or the compared value ("Smith")





Setting class of an Scala object to a field of a Java annotation

I have a Java annotation like the following:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ConvertWith {
  Class<? extends Converter> converterClass();
}

And I have several converter objects written in Scala. For example, IntConverter is shown below:

object IntConverter extends Converter {
  def convert(str: String) = str.toInt
}

I want to use these objects like the following to associate them with fields:

class SampleAction {
  @ConvertWith(converterClass = classOf[IntConverter])
  val x: Int = 0
}

However, Scala cannot find the converter class because scalac compiles objects differently.

I have also tried the following ways but none of them worked:

// error: class type required but IntConverter.type found
@ConvertWith(converterClass = classOf[IntConverter.type])

// error: annotation argument needs to be a constant...
@ConvertWith(converterClass = IntConverter.getClass)

Is there a way to do this? Do you have any ideas?

Thanks in advance.





Get MethodHandle from lambda object

From java.lang.invoke.LambdaMetafactory:

The recommended mechanism for evaluating lambda expressions is to desugar the lambda body to a method, invoke an invokedynamic call site whose static argument list describes the sole method of the functional interface and the desugared implementation method, and returns an object (the lambda object) that implements the target type.

And from inspection this is at least what Oracle JDK does.

My question: given a lambda object is there a way to find the name (or a handle to) the implementation method? Alternately, given a list of implementation methods, is there a way to tell which one corresponds to a given lambda object?





How to get the packagename of fields by reflection?

I'd like to detect fields in my class that either are custom fields (like Address or are native java fields.

Therefore I'm trying to read the package name of each field (to later check if they start with java.*.

public class ReflectionTest {
    public class MyDTO {
        private String name;
        private Address address;
    }

    public class Address {
        private String street;
        private String zip;
        private String town;
    }


    @Test
    public void testPackageName() {
        for (Field field : MyDTO.class.getDeclaredFields()) {
            //always: java.lang.Class
            System.out.println(field.getGenericType().getClass().getPackage().getName()); 
        }
    }
}

Problem: the package shown is always java.lang. Why?





Add properties dynamically at run time in existing class c#

I have a UI from where we are adding following values in a table Fields

  • ProductName
  • ProductId
  • ProductCode

I have a existing class Product with some existing properties

public class Product
{
    public string ProductID { get; set; }
    //product in a product search listing
    public string StoreName { get; set; }
    public string SearchToken { get; set; }

}

I am looking for a method which will add properties in existing class Product at run time (dynamically) when user adds values in a table Fields





How to use reflection on zipped content without extracting

I am able to retrieve list of file inside a zip file by using :

 var files = ZipFile.Open(_buildPath, ZipArchiveMode.Read).
             Entries.Select(x => x.Name).ToArray();

But Need to get the version info of file(s):

var randomEntry= ZipFile.Open(_buildPath, ZipArchiveMode.Read).
     Entries.Where(x => x.Name == "Random.EXE").FirstOrDefault(); 
     FileVersionInfo.GetVersionInfo(randomEntry);

Is there a way I can use reflection on a zip file content.





Can I use GlassMapper's 'Editable' on a reflected property?

I have a model that has a bunch of properties on it named Cause1, Cause2... Cause20 and Symptom1, Symptom2... Symptom20

I can reflect the property values easy enough, but it breaks Experience Editor.

Here's how I'm building my property list:

var causeFuncs = new List<Expression<Func<Northwestern.Areas.Northwestern.ViewModels.ServiceLine.Condition, object>>>();

Enumerable.Range(1, 20).ToList().ForEach(i =>
{
    string propName = "Cause" + i;
    var prop = this.Model.GetType().GetProperty(propName);
    string propValue = prop.GetValue(this.Model, null) as string;

    if(!string.IsNullOrEmpty(propValue))
    {
        causeFuncs.Add(x => prop.GetValue(this.Model, null));
    }
});

And here's my markup:

@foreach (var causeFunc in causeFuncs)
        {
        <span itemprop="cause" itemscope itemtype="http://ift.tt/1Lfu6aX">
            <span itemprop="name">@this.Editable(causeFunc)</span>
        </span>
        }

I didn't expect it to work... and it didn't. This is the error in the browser:

<span itemprop="name"><p>Expression doesn't evaluate to a member value(ASP.ABC_Views_ServiceLine_Condition_cshtml+&lt;&gt;c__DisplayClass1+&lt;&gt;c__DisplayClass3).prop.GetValue(value(ASP.ABC_Views_ServiceLine_Condition_cshtml).Model, null)</p><pre>   at Glass.Mapper.Utilities.GetTargetObjectOfLamba[T](Expression`1 field, T model, MemberExpression&amp; memberExpression) in c:\TeamCity\buildAgent\work\8567e2ba106d3992\Source\Glass.Mapper\Utilities.cs:line 515
at Glass.Mapper.Sc.GlassHtml.MakeEditable[T](Expression`1 field, Expression`1 standardOutput, T model, Object parameters, Context context, Database database, TextWriter writer) in c:\TeamCity\buildAgent\work\8567e2ba106d3992\Source\Glass.Mapper.Sc\GlassHtml.cs:line 572</pre></span>