jeudi 30 novembre 2017

How to obtain entity field tree?

Is there any way to obtain entity field tree? For example, I have

Class A {

    private int id;
    private String name;
    private B objB;

}

class B {
    private int id;
    private String name;
    private C objC;
}

class C {
    private int id;
    privaate String str;
}

So after I run the method, I can have a tree with the field name and type and how deep it is, which looks like below

A
|_________
|    |    |
id  name  B
          |___________
          |     |     |
          id   name   C
                      |____
                      |    |
                      id   str

The idea coming to my mind is reflection, but want to get some guidance/clue on how to do it. Or if there is any other ideas? Thanks in advance.





How to invert/inject dependency - MassTransit Consumer

I'm working on a project and everything is working, but I have one tightly coupled dependency that I don't understand how to invert/inject.

The problem is in my Consumer class, which will receive a command message to start a process, which is part of a global message queue services project, e.g. MyCompany.MQ.Services, yet has a tightly coupled dependency on the process the command message tells it to start, e.g.:

public Task Consume(ConsumeContext<MyMessageInterface> context)
{
    logger = new LoggerConfiguration()
        .WriteTo.Console()
        .CreateLogger();

    try
    {
        TightCoupleProcess tcp = new TightCoupleProcess(context);

        logger.Information("{Blah}, {Blah}, {Blah}", context.Message.exampleVar1, context.Message.exampleVar2, context.Message.exampleVar3);

        tcp.StartProcess();

        return Task.CompletedTask;

    }
    catch (Exception ex)
    {
        return Task.FromException(ex);
    }
}

Task Consume is a part of MassTransit and I cannot modify the signature of Consume as that is actually the implementation of the IConsumer interface of MassTransit.

I guess what I want is a way to invert/inject that dependency so that my global MQ.services project doesn't depend on the project calling it. I think I have some misapprehension about inversion/injection, but I'm not sure how to articulate my shortcomings. Perhaps what I want isn't possible. I know I can't modify the interface implementation, but I'd be cool if something like the following worked, but since Consume is an implementation of a MassTransit interface, I don't think I can inject an anonymous function from my calling class:

public Task Consume(ConsumeContext<MyMessageInterface> context, AnonFunc() func)
{ 
    try
    {
        func(context)

        logger.Information("{Blah}, {Blah}, {Blah}", context.Message.exampleVar1, context.Message.exampleVar2, context.Message.exampleVar3);

        return Task.CompletedTask;

    }
    catch (Exception ex)
    {
        return Task.FromException(ex);
    }
}

I've managed to get around other dependencies such as message type definitions by using reflection and putting this logic in the MQ.Services project, which allows me to keep all process related code outside of the MQ.serives project, e.g.:

    public void PublishMessage(object msg)
    {
        MethodInfo method = this.GetType().GetMethod("InvokePublish");
        MethodInfo generic = method.MakeGenericMethod(msg.GetType());
        generic.Invoke(this, new object[] { msg });
    }

    public void InvokePublish<T>(object msg)
    {
        Task.Run(async () =>
        {
            await busControl.Publish(msg);
        }).Wait();


    }

But I can't apply a similar strategy for the Consumer, almost certainly due to ignorance.

If this is possible will someone please point me in the right direction?





Can't import java.lang.reflect in maven project?

I'm trying to import java.lang.reflect in a java file of a maven project, but I get "error cannot find symbol" on the import line. It can't find java.lang either. This is a built in Java lib, right? I didn't think I needed to add any dependencies for a default java lib. Is there a certain dependency I need to define to gain access to this lib?





Load the class dynamically and get the annotated classes

import com.this.class.Factory;
      public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        // Itearate over all @Factory annotated elements
        for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) {
            ...
        }
      }

This works when I import the annotation class in the annotation processor. But when the annotation class is loaded dynamically doesn't works

Class<?> Factorry = class.forName("com.this.class.Factory")
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        // Itearate over all @Factory annotated elements
        for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) {
            ...
        }
      }

How to pass the annotated Factory.class to getElementsAnnotatedWith when the class is loaded using class.forName()





Can I use reflection to instantiate properties that inherit from a generic type? (C#)

I was wondering if there was a tidy way to use reflection to instantiate a bunch of properties in a class, with a constraint that the property types to instantiate should only inherit from certain classes, and what if one of these classes has a generic type parameter.

For example.....

public class Control
{
    public string Name => "Test Name";
}

public abstract class BasePage<T> { }

public class HomePage : BasePage<HomePage> { }

public class LoginPage : BasePage<LoginPage>
{
    public Control Test { get; set; } = new Control();
}

public class LoginLinkPage : BasePage<LoginLinkPage>
{
    public Control Test { get; set; } = new Control();
}

public class UserPage : HomePage
{
    public Control Test { get; set; } = new Control();
}

public class Pages
{
    public UserPage UPage { get; set; }
    public LoginPage LPage { get; set; }
    public LoginLinkPage LLPage { get; set; }
} 

Is it possible to instantiate all the properties in Pages in a single method? And allow for more properties to be added and instantiated assuming they inherit from either BasePage<T> or HomePage?

This is what I have so far, but it only checks the subclass of the property type is homepage...

class Program
{
    public static void InitializeControls<T>(T page)
    {
        var pageType = typeof(T);

        var properties = pageType.GetProperties().Where(p => p.PropertyType.IsSubclassOf(typeof(HomePage)));

        foreach (var property in properties)
        {
            property.SetValue(page, Activator.CreateInstance(property.PropertyType));
        }
    }

    static void Main(string[] args)
    {
        var pages = new Pages();

        InitializeControls(pages);

        Console.WriteLine(pages.UPage.Test.Name); // "Test Name"
        Console.WriteLine(pages.LLPage.Test.Name); // NullReferenceException
        Console.WriteLine(pages.LPage.Test.Name);  // NullReferenceException       

        Console.ReadLine();
    }
}

I can't wrap my head around whether it's possible to also do a check for BasePage<T>, if T could be various different types.

I would be open to design changes that might solve this problem.

Thanks,





Strange java.lang.ClassCastException when using [] call.

I'm using LibDGX library for my game. And i faced common exception ClassCastException, but it occurs in strange case.

I'm using Animation class from LibGDX library.

I'm getting error on this line only if i am using [] operation.

val tex = animation.keyFrames[0]

If i change it to get() error disappears.

tex = animation.keyFrames.get(0)

Here is full method. I simplified example.

override fun create() {


    val frames = Array<TextureRegion>()
    frames.add(TextureRegion(Texture("badlogic.jpg")))

    val animation = Animation(frames)

    val tex1 = animation.keyFrames.get(0)  // Compiles

    val tex = animation.keyFrames[0]  // error - [Ljava.lang.Object; cannot be cast to [Lcom.badlogic.gdx.graphics.g2d.TextureRegion;


}

Strange, isn't it?

Here is Animation class that i used to minimise other error reasons. It is exactly the same as in LibGDX api.

    public class Animation<T> {

    T[] keyFrames;


    public Animation (Array<? extends T> keyFrames) {

        Class arrayType = keyFrames.items.getClass().getComponentType();
        T[] frames = (T[]) ArrayReflection.newInstance(arrayType, keyFrames.size);
        for (int i = 0, n = keyFrames.size; i < n; i++) {
            frames[i] = keyFrames.get(i);
        }

        setKeyFrames(frames);
    }

    protected void setKeyFrames (T... keyFrames) {
        this.keyFrames = keyFrames;
    }
}

I also noticed that error disappears if i use Array.with construction instead of creating Array<TextureRegion>

val animation = Animation(Array.with(TextureRegion(Texture("badlogic.jpg"))))

Could you tell me the reason why this occurs or it is possible a bug?





How to call a form constructor with reflection

_myCrudName is the name of the form I would like to open. below code works just fine how ever what I would like to do here is pass my DbContext to the MyCrud's Constructor. how do I do that? any help is appreciated

            var type = Type.GetType(_myCrudName);
            var MyForm = Activator.CreateInstance(type) as MyCrud;
            if (MyForm == null) return;

            using (MyForm)
            {
                MyForm.MyPrimaryKey = _myPrimaryKey;
                MyForm.MyPkValue = MyPkValue;

                MyForm.ShowDialog();
            }





MEF Export Provider throws exception

I am receiving the following exception when trying to import a type that uses an Export Provider:

ImportDefinition of type 'System.ComponentModel.Composition.Primitives.ContractBasedImportDefinition' cannot be used in this context. Only import definitions produced by the ReflectionModelServices.CreateImportDefinition are supported.

    protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
    {
        if (definition.ContractName == typeof(Interface.ILogger).FullName)
        {
            try
            {
                string typeName = null;
                if (ReflectionModelServices.IsImportingParameter(definition))
                {
                    Lazy<System.Reflection.ParameterInfo> paramInfo = ReflectionModelServices.GetImportingParameter(definition);
                    typeName = paramInfo.Value.Member.ReflectedType.FullName;
                }
                else
                {
                    LazyMemberInfo info = ReflectionModelServices.GetImportingMember(definition);
                    typeName = info.GetAccessors()?.FirstOrDefault()?.ReflectedType.FullName;
                }

                return new Export[] { new Export(definition.ContractName, () => { return LogManager.GetLogger(typeName, typeof(PassthroughLogger)); }) };
            }
            catch (ArgumentException) { }
        }
        return Enumerable.Empty<Export>();
    }

The exception is thrown when it reaches

ReflectionModelServices.IsImportingParameter(definition)





Get Markupextension expression in wpf via reflection

I try to parse xaml file (WPF) with LogicalTreeHelper. The LogicalTreeHelper gives me each control as DependancyObject. And I need to investigate which static resources be used with a control.

The Example of an xaml:

<Label Grid.Row="0" Grid.Column="0" Margin="{StaticResource MarginExtraSmall}"
       VerticalAlignment="Center" Content="{x:Static p:Resources.Type}" ></Lable>

The problem is, when I try to get a value of the "Content" property of the Control "Label", I recieve a string, but I need a markupextension expression insteed, in this case "{x:Static p:Resources.Type}"

Have anybody an idea how to solve the problem?

Thank you! Leonid





How to load a class file dynamically and pass it as a parameter

Static Implementation

import com.this.class.ImportedClass;
getElementsAnnotatedWith(ImportedClass.class)

the above method call works when I use import, but when I want to load the same class dynamically

ImportedClass Class = Class.forName("com.this.class.ImportedClass");
getElementsAnnotatedWith(importedClass.class)

When I pass the .class file it wont take the parameter.





C# Reflection - Choose Which Overload of a Particular Method to run Based on Number of Parameters

I have a class which has a method with a number of overloads as follows

class MyClass
{
    public bool DoSomething(string linkedServerName, string serverName, string instanceName, string userName, string Password)
    {
        // OverLoad1
        // do stuff
    } 
    public bool DoSomething(string linkedServerName, string serverName, string instanceName)
    {
        // OverLoad2
        // do stuff
    } 
    public bool DoSomething(string linkedServerName, string serverName, string userName, string Password)
    {
        // OverLoad3
        // do stuff
    } 
    public bool DoSomething(string linkedServerName, string serverName)
    {
        // OverLoad4
        // do stuff
    } 
    private bool DoSomething(List<SqlParameter> parms)
    {
        // OverLoad5
        // do stuff
    } 
}

In another class, I have a button click event handler which builds an List of the parameters that should be passed to the above methods, based on user input:

public class MyForm : Form
{
    // code...

    private void Button1_Click(object sernder, EventArgs e)
    {
         List<String> parms = New List<String>();
         //code here which will populate the above list with values dependant on which text boxes the user has filled in

         Type t = new MyClass().GetType();
         Type[] ts = new Type[parms.Count];

         for (int i=0; i< parms.Count; i++)
         {
             ts[i] = typeof(string);
         }

         System.Reflection.MethodInfo m = t.GetMethod("CreateLinkedServer",ts)

         // how do I invoke the method referenced in m??
    }
}

I've got the method I want to invoke which is referenced in the variable m but I'm not sure how to invoke. I know the MethodInfo class has an Invoke method and I've tried:

m.Invoke();
m.Invoke(m, ts);
m.Invoke(this, ts);

and neither of them have worked





how can i find all the methods that are called by reflection

As title, I want to find all methods that are called by reflection in a Java Application.

I came up with a solution that has not yet been implemented.

Read the contents of the class file, start from the instruction, find the Method#invoke instruction, and then look back to find the instance that calls the method, and then get the instance corresponding Class and MethodName.

However, this method has a problem, if Class or MethodName or even Method are passed as a parameter, it is difficult to find the corresponding content.

On this basis, think of ways to improve, traverse all the methods, check the instructions of the method. If got Method#invoke instruction in method A(), and Class and MethodName are passed in as parameters, record method A() and the order of parameters. In the following check, if there is a method call A(), you can get the value passed to method A() Parameters, to obtain the required value.

However, this solution requires traversing the entire program's instructions, which can be very time-consuming when the program is very large. If method call too many levels, the implementation of the algorithm can be quite complicated. So would like to ask, the feasibility of this idea, or is there any better way to solve the problem.

Thanks in advance.





mercredi 29 novembre 2017

How to pass test class name as input parameter using java reflection in testNG?

Currently am executing testNG scripts through jenkins, in my code base am having around 75 test class, but i want to run specific test cases only. For achieving this i need to pass the test class name to testNG.XML. We can achieve this through reflection, but i dont know how to proceed with this.





Access private field in Companion object

I have a class TestClass with a companion object. How can I access a private field say xyz in the companion object using runtime reflection in scala when that private field is set from within the class as shown below.

class TestClass {  TestClass.xyz = 100 }
object TestClass { private var xyz: Int = _ }

I tried the following

import scala.reflect.runtime.{currentMirror, universe => ru}
val testModuleSymbol = ru.typeOf[TestClass.type].termSymbol.asModule
val moduleMirror = currentMirror.reflectModule(testModuleSymbol)
val instanceMirror = currentMirror.reflect(moduleMirror.instance)
val xyzTerm = ru.typeOf[TestClass.type].decl(ru.TermName("xyz")).asTerm.accessed.asTerm
val fieldMirror = instanceMirror.reflectField(xyzTerm)
val context = fieldMirror.get.asInstanceOf[Int]

But I was getting the below error.

scala> val fieldMirror = instanceMirror.reflectField(xyzTerm)
scala.ScalaReflectionException: Scala field xyz  of object TestClass isn't represented as a Java field, nor does it have a
Java accessor method. One common reason for this is that it may be a private class parameter
not used outside the primary constructor.
  at scala.reflect.runtime.JavaMirrors$JavaMirror.scala$reflect$runtime$JavaMirrors$JavaMirror$$abort(JavaMirrors.scala:115)
  at scala.reflect.runtime.JavaMirrors$JavaMirror.scala$reflect$runtime$JavaMirrors$JavaMirror$$ErrorNonExistentField(JavaMirrors.scala:127)
  at scala.reflect.runtime.JavaMirrors$JavaMirror$JavaInstanceMirror.reflectField(JavaMirrors.scala:242)
  at scala.reflect.runtime.JavaMirrors$JavaMirror$JavaInstanceMirror.reflectField(JavaMirrors.scala:233)
  ... 29 elided

This exception is thrown only when I refer the variable xyz in the TestClass (ie TestClass.xyz = 100). If this reference is removed from the class than my sample code works just fine.





Ceylon metamodel

I am studying Ceylon and have question about it metamodel. I want to create some create some base class 'DataContainer' which allow to instantiate immutable classes with build-in equals-hash implementation: e.g. Identifier(125, "ab") == Identifier(125, "ab") So base class should collect all shared non-variable values and use this information in 'hash' an 'equals' methods. I have wrote this code:

shared abstract class DataContainer(ClassDeclaration declaration) {
    value members = {
        for (i in declaration.memberDeclarations<ValueDeclaration>())
            if (!i.variable, i.name != "hash", i.name != "string") i
    };
    variable Integer? hashCode = null;

    shared actual Boolean equals(Object that) {
        if (is DataContainer that) {
            for (item in members) {
                value thisMember = item.memberGet(this);
                value thatMember = item.memberGet(that);
                if (exists thisMember, exists thatMember) {
                    if (thisMember != thatMember) { return false; }
                } else if (thisMember exists != thatMember exists) { return false; }
            }
            return true;
        }
        return false;
    }

    shared actual Integer hash => hashCode else (hashCode = calculateHash());

    Integer calculateHash() {
        variable value result = 0;
        for(i in members) {
            if (exists member = i.memberGet(this)) {
                result = result.xor(member.hash);
            }
        }
        return result;
    }
}

class Identifier(shared Integer? id, shared String? name) extends DataContainer(`class`) {}

The Identifier class is the client of DataContainer. I like this solution in whole but I have to pass 'class' into the super class constructor because if I use 'class' inside DataContainer it doesn't see any members of subclass. How can I obtain actual list of extended class's members in base class methods? Something like 'this' doesn't work...





How do I get class annotations from a Method instance?

Consider the following class:

@ClassAnnotation1
@ClassAnnotation2
class MyClass {

    // ...        

    @MethodAnnotation1
    @MethodAnnotation2
    private void myMethod(@ParamAnnotation1 @ParamAnnotation2 int i) {
    // ...
    }
}

During a reflection phase of my application, I need to analyze various code aspects, given a Method instance.

public void analyze(final Method method) {
    // do the analysis...
}

I can easily analyze the parameters' Annotation by doing

for (Parameter p : method.getParameters()) {
    if (p.getAnnotation(ParamAnnotation1.class) != null) {
        // ...
    }
}

and get the results I expect.

The method's Annotation's can easily be processed with

method.getAnnotation(MethodAnnotation1.class)


Unfortunately I fail to get the expected results for the class' Annotation's.

In fact, the call to method.getClass().getAnnotation(ClassAnnotation1.class) return null, whereas MyClass is clearly annotated by @ClassAnnotation1.

How do I get the MyClass annotations from a Method instance?





mardi 28 novembre 2017

Fastest way to compute an expression func result given parameters

I receive an Expression<Func<...,...,...,TResult>> (random, but fixed number of parameters) instance in a form of a general Expression type.

For instance:

Expression<Func<int,int,int>> adderExpression = (a,b) => a+b;
Expression receivedExpression = adderExpression;
//Later on, I get only the receivedExpression variable and an array of values for which I have to compute:
var values = new object[] {3, 4};
var result = receivedExpression.Compile().DynamicInvoke(values);

The only thing I have access to is the receivedExpression variable and an array of object values for which I have to compute the result of applying the compiled expression.

The receivedExpression does not change: once I get it, it remains the same.

What is the fastest way I can compute the result variable given my circumstances? DynamicInvoke is super slow in this case, and I was wondering if there is a faster way to compute the result.





Golang: Cannot use implementation of interface as argument to func that wants interface

I'm getting the following error:

./main.go:31: cannot use telegramService (type messaging.TelegramService) as type mypackage.MessagingService in argument to mypackage.RegisterMessagingService:
    messaging.TelegramService does not implement mypackage.MessagingService (wrong type for HandleIncomingMessage method)
        have HandleIncomingMessage(telegram.Message) error
        want HandleIncomingMessage(mypackage.IncomingMessage) error

I have an interface that describes a messaging service like Telegram or WhatsApp, and an interface that describes an incoming message from one of those services:

// IncomingMessage is a message that comes in on a messaging service
type IncomingMessage interface {
    Send() error
}

// MessagingService is a service on which messages can be send (like Telegram or FB Messenger)
type MessagingService interface {
    Start()
    HandleIncomingMessage(IncomingMessage) error
    GetHTTPHandler() http.HandlerFunc
    GetCommands() []MessagingCommand
}

The first implementation of MessagingService is for Telegram. The issue is the HandleIncomingMessage function, which currently doesn't really do anything and just looks like this:

// HandleIncomingMessage will take an incoming message and repond to it
func (s TelegramService) HandleIncomingMessage(msg *telegram.Message) error {

    return nil
}

The issue is that this function accepts a telegram.Message, which the compiler says doesn't comply with the interface. The thing is, that telegram.Message is an implementation of IncomingMessage:

// Message is a Telegram message
type Message struct {
    // Added the line below at some point, but it didn't work without it either
    mypackage.IncomingMessage
    MessageID uint64 `json:"message_id"`
    FirstName string `json:"first_name"`
    Username  string `json:"username"`
    Date      uint64 `json:"date"`
    Text      string `json:"text"`
    Chat      Chat   `json:"chat"`
    From      User   `json:"from"`
}

// Send will take m and send it
func (m Message) Send() error {
    // Do stuff

    return nil
}

Initially IncomingMessage was an empty interface, which is where I first noticed the issue. I tried adding the function Send() which I was going to add anyway, as I thought maybe just giving it any struct wouldnt't work. However, I'm still getting this error.

I don't see any reason why telegram.Message doesn't implement the interface, it's pretty straight forward.

Can anyone explain why this doesn't work?

PS: My package isn't actually called mypackage, changed for clarity





Reading Custom Attributes of a .Net class property in Javascript

I have a .Net class with some properties. In some of the properties, I use Custom Attributes. For e.g.

   <UserDefined(true)>_
   Property Name as string

I Use webservices and JSON to retrieve an instance of this class on my web-forms client side and use Java-script extensively. Is there a way in Java-script object to identify whether a Property has any Custom Attribute defined and its value? I tried Property Description of the Object class in JS, but it just gives the property name and its value, not any Attributes of that Property.





ClassNotFoundException when loading classes from a jar file with reflection

I load classes at runtime from a .jar file using the following code:

try
{
    // Get all the files in mod folder
    File[] mods = new File("mod").listFiles();

    for (int i=0; i<mods.length; i++)
    {
        // Skip if the file is not a jar
        if (!mods[i].getName().endsWith(".jar"))
            continue;

        // Create a JarFile
        JarFile jarFile = new JarFile(mods[i]);

        // Get the entries
        Enumeration e = jarFile.entries();

        // Create a URL for the jar
        URL[] urls = { new URL("jar:file:" + mods[i].getAbsolutePath() +"!/") };
        cl = URLClassLoader.newInstance(urls);

        while (e.hasMoreElements())
        {
            JarEntry je = (JarEntry) e.nextElement();

            // Skip directories
            if(je.isDirectory() || !je.getName().endsWith(".class"))
            {
                continue;
            }

            // -6 because of .class
            String className = je.getName().substring(0,je.getName().length()-6);
            className = className.replace('/', '.');

            // Load the class
            Class c = cl.loadClass(className);
        }
    }
}
catch (Exception e)
{
    e.printStackTrace();
}

After loading the classes, I need the files available via reflection:

getClassLoader().loadClass(packageName + "." + className.replace('.', '$'))

However, this second line is done by a library which I cannot change. So I need to adapt my code (the upper code block) to load the classes in a way it would be available to the classloader of the external library I'm using (JavaFX, by a reference in a fxml file). How can I do this?





What is a java.lang.reflect.Field#slot?

Does java.lang.reflect.Field#slot hold a sequence number in the order how fields were declared in the source file?
I know its private and I should not use it and stuff but anyway...





Scala get classtag from class instance

I need to write a generic method to get all fields of an object and it's value, the class of this object may contains ClassTag, so we should find a way to get it as well, is any way good way ? the difficulty is we don't know the class ahead, it may contains ClassTag (zero to many), It may not.

For example,

class A(x : Int) {}

a = new A(1)

We should output x => 1

class B[T: ClassTag]() {}

b = new B[Float]()

We should output _$1 = Float





ReflectionTypeLoadException and COM-Interop

I have a .Net4 assembly which exposes an abstract, base class. In that same assembly, I haver some code which reflects over all the files in a folder to build up a list of classes inheriting that base class. Here's the salient routine

private JsonTextWriter GetAvailableServices(JsonTextWriter writer, string path)
    {
        try
        {            
            writer.WriteStartArray();
            writer = new DirectoryInfo(path).GetFiles(FileFilter)
                                            .Where(f => IsAssembly(f.FullName))
                                            .Select(f => Assembly.LoadFile(Path.Combine(path, f.Name)))
                                            .SelectMany(a => GetLoadableTypes(a))
                                            .Where(p => typeof(ServiceProxy).IsAssignableFrom(p) && !p.IsAbstract)
                                            .Select(a0 => new { Instance = Activator.CreateInstance(a0), ClassName = a0.ToString() })
                                            .Aggregate(writer, (s, v) =>
                                            {
                                                s.WriteStartObject();
                                                s.WritePropertyName(ClassnameLabel);
                                                s.WriteValue(v.ClassName);
                                                s.WritePropertyName(DescriptionLabel);
                                                s.WriteValue(((ServiceProxy)v.Instance).Description);
                                                s.WriteEndObject();
                                                return s;
                                            });                
        }
        catch { Exception ex; }
        finally
        {
            writer.WriteEndArray();                
        }

        return writer;
    }

 private IEnumerable<Type> GetLoadableTypes(Assembly assembly)
    {            
        try
        {
            return assembly.GetTypes();
        }
        catch (ReflectionTypeLoadException e)
        {
            return e.Types.Where(t => t != null);
        }
    }       

I have a unit test which runs this code, targetting a specific folder, and it all works fine returning a list of classes inheriting the base class as JSON.

The above code sits in an assembly which is to be invoked from a COM (VB6) component. If I now invoke this same code from COM, targetting the same folder which the unit test targets, I get the reflection error and the loader info reports that it can't load the assembly which contains the above code. This only occurs in the GetLoadableTypes routine on the GetTypes() call when I am reflecting over an assembly which contains classes which do inherit the base class.

It sounds almost like a re-entrancy issue which only arises when COM is involved. I guess I could put the abstract base class into another assembly but wondered if there was something else going on.

Any explanation or pointers obviously gratefully received





lundi 27 novembre 2017

How to fully block reflection in java

I would like you to tell me how to fully block the reflection in private fields in java. I know wa can block it with checking the caller class but this only in privates methods but not in private fields like a String/int etc..

Thank you !





c# reflection - convert string to type of FieldInfo.GetType()

I have an app that loads settings from the command line, they come as strings, but i might have a lot of settings at some time.

I have this so far.

class Settings
{
    public static int TestSetting;

    public static void Load(string[] settings)
    {
        FieldInfo[] fields = typeof(Settings).GetFields();

        foreach(string setting in settings)
        {
            string[] settingSplit = setting.Split('=');

            string settingName = settingSplit[0];
            string settingValue = settingSplit[1];

            foreach(FieldInfo field in fields)
            {
                if(field.Name == settingName)
                {
                    field.SetValue(null, Convert.ChangeType(settingValue, field.GetType()));
                }
            }
        }

        Console.WriteLine(TestSetting);
    }
}

Should be used like this:

Settings.Load(new string[] { "TestSetting=13" });

So as you can see i first get all the FieldInfo's from my Settings class, then i iterate through the settings, each setting is composed of "SettingName=SettingValue" and for each i verify if its name is the same as the field's, if it is then i try to convert the string to the field type, it fails with:

System.InvalidCastException occurred
Invalid cast from 'System.String' to 'System.Reflection.RtFieldInfo'.





How to get the value of associate field using reflection

class A {

     private String someField;

     @validation
     private String annotatedField;
}

I'm implementing a custom constraint validation annotation @validation to validate annotatedField. I need to know the value of someField to satisfy the logic of my validation.

Validator implements ConstraintValidator<validation, String>{

      @Override
      public void initialize(validation constraintAnnotation) {

      }

      @Override
      public boolean isValid(String annotatedField, ConstraintValidatorContext context) {

           if (StringUtils.isBlank(annotatedField)) {
                return true;
           }

           String someField; // get some someField value given the annotatedField

      }
}

Is there a way to do this using reflection?





Is it still possible to use java.misc.Unsafe in Java 9?

Until Java 8 it was possible to obtain the singleton java.misc.Unsafe instance via a method like the following:

public static Unsafe getUnsafe() {
    try {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        return (Unsafe) f.get(null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

Even though it was highly suggested not to use Unsafe, many vendors and libraries use it internally.

Now, with Java 9 and Jigsaw, I think that also the way Unsafe is handled has changed. I read some posts with contrary information. Some say it has been completely hidden and it is not even retrievable, others say one has to enable a VM flag, while others write that it should be officially support now.

So: Is it possible to still use java.misc.Unsafe in Java 9, and if so, how?





dimanche 26 novembre 2017

How to set the property value using reflection in C# when the property is a delegate type?

I have a property in a dll that i am using using Reflection feature in C#. I would like to set the property and the property type is a delegate type.

Please let me know the steps involved in setting the property using the Reflection.

I know that SetValue method need to be used to do this, but don't know how to set the property of the delegate type.

SetValue(objectName, 1, null) is to set an integer property using reflection, but don't know how to set the property of the delegate type.

How to declare a variable of the delegate property type and initialize it using reflection?

Please provide solution with an example.

Thanks, Raghu Devisetti





java-why new() slower than newInstance()

i know that if i create new objects with reflection,it is very slow ,so i test it.but the result makes  me puzzled,newInstance() is faster than new(),my jdk version is java version "1.8.0_77".

public class Test {

static class B {
}

public static long timeDiff(long old) {
    return System.nanoTime() - old;
}

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

    int numTrials = 10000000;
    B[] bees1 = new B[numTrials];
    Class<B> c = B.class;
    long nanos;
    nanos = System.nanoTime();
    for (int i = 0; i < numTrials; i++) {
        bees1[i] = new B();
    }
    System.out.println("Normal instaniation took: " + TimeUnit.NANOSECONDS.toMillis(timeDiff(nanos)) + "ms");
    B[] bees2 = new B[numTrials];
    nanos = System.nanoTime();
    for (int i = 0; i < numTrials; i++) {
        bees2[i] = c.newInstance();
    }
    System.out.println("Reflecting instantiation took:" + TimeUnit.NANOSECONDS.toMillis(timeDiff(nanos)) + "ms");

}

}

the result:

  • Normal instaniation took: 2363ms
  • Reflecting instantiation took:1679ms.

so i don't know why..who can explain it ?





Can Globalization Work Without Localization in Asp.net?

According to MSDN Globalization is the process of designing and developing a software product that functions in multiple cultures/locales." "Localization is the process of adopting a globalized application, which you have already processed for localizability, to a particular culture/locale

But my question is can a web application work in which only globalization is defined not localization?

any theoretical example will be welcome...





samedi 25 novembre 2017

Converting interface into another and copy content

I've got the following method:

func ValidateParam(conf map[string]interface{}, paramName string, out interface{}) error {
    param, ok := conf[paramName]

    if !ok {
        return errors.New("some error")
    }

    // ...
}

I would like to be able to call it like so:

myVar := "some text"
err := ValidateParam(conf, "my_var_param", &myVar)

myOtherVar := &MyStruct{}
err := ValidateParam(conf, "my_struct_param", myOtherVar)

The idea is:

  • Get the param using the conf map
  • Check that this param could be converted into the same type as out
  • Hydrate out using the param

=> It is kind of the same process as for json.Unmarshal(data, &myVar) or when doing a query with mgo query.Collection("col").One(&myVar)

I can't find how to achieve this, any help would be more than welcome.

Cheers





Why is it thrown java.lang.InstantiationException?

Look at following code:

public class Outer {
    public static void main(String[] args) throws Exception {
        new Outer().greetWorld();
    }

    private void greetWorld() throws Exception {
        System.out.println(Inner.class.newInstance());
    }

    public class Inner {
        public Inner () {}
        public String toString(){
            return "HelloWorld";
        }
    }
}

Why is it thrown java.lang.InstantiationException ?
After all, nested class Inner has nully constructor. Can someone explain it?





vendredi 24 novembre 2017

Build expression from object

I have the following object received from Angular client application in ASP.NET Core:

public class ModelFromClient
{
  public string name {get;set;}      //Database field is Name
  public int qunatity {get;set;}     //Database field is Quantity
}

And I have a EF Table class:

[Table("MyTable")]
public class MyRow
{
  public int Id {get;set;}  
  public string Name {get;set;}
  public int Qunatity {get;set;}
}

Now I need to create expression from ModelFromClient to Expression<Func<MyRow, MyRow>> and I need it with generic. Without generics solution would be:

public Expression<Func<MyRow, MyRow>> ToExpression(ModelFromClient Model)
{
    Expression<Func<MyRow, MyRow>> result = (t) => new MyRow()
    {
        Name = Model.name, 
        Quantity = Model.qunatity
    };
    return result;
}

But I would like something like that:

public Expression<Func<T, T>> ToExpression<T>(object Model) where T: new()
{
    Expression<Func<T, T>> result = (t) => new T();
    foreach(var prop in Model.GetType().GetProperties()) 
    {
       //compile error Fields does not exists.
       result.Body.Fields.Add(prop.Name.Capitalize(), prop.GetValue(Model, null));  //capitalize returns Name from input name
    }
    return result;
}

I need expression to pass it to Update extension method of EntityFramework-Plus.





How to invoke a method inside a external jar using reflection

I want to invoke a method which inside a external .jar by using reflection.

This is a sample code which inside the jar.

public class HelloFunction implements Runnable, RequestHandler<Request> {

    @Override
    public void handle(final Request request) {
        System.out.println("handle : " + request);
    }

    @Override
    public void run() {
        System.out.println("run......");
    }
}

Then i loaded this jar in a separate java program and tried to invoke HelloFunction.handle() method. This is the sample code for that part.

public class App {

    public static void main(String[] args) {
        test();
    }

    public static void test(){

        try{

            final Class<?> functionClass = getClassFromFunctionJar("com.hello.HelloFunction");

            final Object functionClassObject = functionClass.newInstance();

            if(functionClassObject instanceof RequestHandler){

                @SuppressWarnings("unchecked")
                final RequestHandler<Object> handler = RequestHandler.class.cast(functionClassObject);

                final Object inputObject = getRequestClass(functionClass).newInstance();

                handler.handle(inputObject);


            }

        }catch(final Exception e){

            System.err.println(e.getMessage());

        }
    }

    public static Class<?> getRequestClass(final Class<?> cls) throws FunctionInvokerException{

        try{
            final Type[] types = cls.getGenericInterfaces();

            for(Type type : types){

                //check RequestHandler
                if(type.getTypeName().contains(RequestHandler.class.getName())){

                    final ParameterizedType parameterizedType = (ParameterizedType) type;

                    // [0]=> Request Type
                    final String inputClassName = parameterizedType.getActualTypeArguments()[0].getTypeName();
                    return getClassFromFunctionJar(inputClassName);

                }

            }

            throw new Exception("UNABLE_TO_FIND_REQUEST_TYPE");

        }catch(final Exception e){
            throw new FunctionInvokerException(e);
        }

    }

    private static Class<?> getClassFromFunctionJar(final String className) throws ClassNotFoundException, MalformedURLException{
        final ClassLoader classLoader = URLClassLoader.newInstance(new URL[]{new URL("file:" + "/jar-location/hello.jar")}, App.class.getClassLoader());
        return Class.forName(className, true, classLoader);
    }

}

You can see here i used getClassFromFunctionJar() method to load Class from a jar. And getRequestClass() method is used to find class type of the HelloFunction.handle() method's input parameter. Everything is fine until invoking handle() method.

Finally i got an error which says "com.hello.Request cannot be cast to com.hello.Request". Could you please help me to solve this issue.





jeudi 23 novembre 2017

How can I set my class properties values Using Reflection

Good Day,

Lets say this is my class:

public class MyClass {

    public bool boolProp { get; set; }
    public string stringProp { get; set; }
}

this is my IDictionary:

IDictionary<string, string> myDict= 
        new IDictionary<string, string>();

myDict.Add("boolProp", "true");
myDict.Add("stringProp", "teststring");

So I want to update my class properties using Reflection where my dictionary keys matches the name of property then set its value by creating a method, how is that?

Method parameter should be like this:

public void UpdateProperties(IDictionary<string, string> myDict) {

Thanks





Get solution details from running debugger in C#

I'm working on a tool which will check a configuration file for a large system.

In order to do this, I want to look for all references to a particular method (the one responsible for loading a value from the config object), and check that all the parameters from each instance of the call are present in the config object and are permissible for loading on a named system.

The config file is only ever created by one application, which will be run from a known directory. It reflects all DLLs in the directory to return all instances of the method call which loads a property in order to create a list of all properties used by the system for validation.

This approach works when running from the installation directory, however durning development, I will need to run the tool from the IDE.

When running from the IDE, I want to find the name of the open solution file so that I can retrieve the subordinate projects and get all references to the config object.

Is it possible to get the name of the solution file from an instance of the debugger running in the IDE (VS2013 in this case).





InvocationTargetException exceptions seen

I am using reflections API to invoke a class run time and invoke its methods. But am seeing java.lang.reflect.InvocationTargetException exceptions.

I need to invoke a class called - TestClass, and invoke its method execute by passing an HashMap qualityCheckData which contains data in K, V pairs after reading data from database.

JDBCDBReader:

public void runSQLQueriesValidate()    {
    ....
        try {
            Class[] paramHash = new Class[1];
            paramHash[0] = HashMap.class;
            Class cls = Class.forName("<package name>" + className);
            Object obj = cls.newInstance();
            Method method;
            while(re.next()) {
                 ...
                qualityCheckData.put(metaData.getColumnLabel(i).toString(),  insertData);
            }
            method = cls.getDeclaredMethod("execute", paramHash);
            try {
                    method.invoke(obj, qualityCheckData);
                    if (Boolean.parseBoolean((String) returnV) == true) {
                        test.log(LogStatus.INFO, "Returned true");
                    }
            }
            catch(Exception e)  {
                    test.log(LogStatus.FATAL, "Exception seen, please investigate " + e + Arrays.asList(e.getStackTrace()).stream().map(Objects::toString).collect(Collectors.joining("\n   " )));
            }
        } catch(Exception e) {
              ...
     }

TestClass:

public class TestClassextends BasePage {
    public HashMap<String, String> map = new HashMap<String, String>();
    public TestClass(){}

    public TestClass(ExtentTest test)   {
        super(test);
    }

    public boolean execute(HashMap<String, String> map) {
        test.log(LogStatus.INFO, "Inside execute");
        setMap(map);
        return true;
    }

    public HashMap<String, String> getMap() {
        return map;
    }

    public void setMap(HashMap<String, String> map) {
        this.map = map;
    }
}

Exception:

java.lang.reflect.InvocationTargetException
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    java.lang.reflect.Method.invoke(Method.java:498) 
    com.test.data.validation.table.JDBCDBReader.runSQLQueriesValidate(JDBCDBReader.java:226) 
    com.test.data.validation.test.CoreTestcases.Test.connEstablish(Test.java:81) 
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    java.lang.reflect.Method.invoke(Method.java:498) 
    org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85) 
    org.testng.internal.Invoker.invokeMethod(Invoker.java:639) 
    org.testng.internal.Invoker.invokeTestMethod(Invoker.java:821) 
    org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1131) 
    org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:124) 
    org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108) 
    org.testng.TestRunner.privateRun(TestRunner.java:773) org.testng.TestRunner.run(TestRunner.java:623) 
    org.testng.SuiteRunner.runTest(SuiteRunner.java:357) 
    org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352) org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
    org.testng.SuiteRunner.run(SuiteRunner.java:259) 
    org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) 
    org.testng.TestNG.runSuitesSequentially(TestNG.java:1185) 
    org.testng.TestNG.runSuitesLocally(TestNG.java:1110) org.testng.TestNG.run(TestNG.java:1018) 
    org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:283) 
    org.apache.maven.surefire.testng.TestNGXmlTestSuite.execute(TestNGXmlTestSuite.java:75) 
    org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:120) 
    org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:373) 
    org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:334) 
    org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:119) 
    org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:407)





C# Reflection: Cannot convert type 'System.Reflection.PropertyInfo' to

Morning,

I am trying to use reflection to iterate all properties in one of my classes :

public MDInstrument() : base()
    {
        PropertyInfo[] properties = typeof(MDInstrument).GetProperties();

        foreach (PropertyInfo item in properties)
        {
            var tick = item as TickData;
        }
    }

when I inspect the var properties I can see all the properties correctly

enter image description here

but on the line:

 var tick = item as TickData;

I am getting the error:

enter image description here





mercredi 22 novembre 2017

Why is my private constructor public when checked with reflection?

I have (among many other Util classes which do not have this problem) a class FileUtil which fails the test for having a private constructor.

The class definition is:

public final class FileUtil {

    /**
     * Hidden constructor to prevent instantiation.
     */
    private FileUtil() {
    }
    // ...
    // many static methods
}

As mentioned above I have many other classes which are tested for having private constructors. The test method is:

@Test
public void testPrivateConstructor() throws Exception {
    Constructor<FileUtil> constructor = FileUtil.class.getDeclaredConstructor();
    Assert.assertTrue("Constructor is not private", Modifier.isPrivate(constructor.getModifiers()));
    constructor.setAccessible(true);
    constructor.newInstance();
}

But for this class - and only for this class - the isPrivate() method returns false and if checking in the debugger the constructor indeed is shown as public. However, if trying to call the constructor programmatically, Eclipse tells me the method is not visible.

I'm working with Eclipse and Maven and the problem shows in Eclipse and also on the command line when calling the Maven build. So it's really a Java problem, but as I use this pattern throughout my library without problems I do not see why it fails with this class only.

Any thoughts?





How to access attributes/methods in generic class parameter

New to Kotlin coming from C#.

I am trying create a class that takes in an interchangeable class object through generics. In the class I would like to access attribute values and call methods in the class. I assume this has to be through some kind of reflection mechanism. Digging through Kotlin references I have been trying to apply suggestions to my code, however I get some cryptic errors.

Any help is appreciated.

Error:(35, 20) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
@InlineOnly public operator inline fun <T> Lazy<T1?>.getValue(thisRef: Any?, property: KProperty<*>): T1? defined in kotlin
@InlineOnly public operator inline fun <V, V1 : T1?> Map<in String, T1?>.getValue(thisRef: Any?, property: KProperty<*>): T1? defined in kotlin.collections
@SinceKotlin public fun <K, V> Map<Class<T1>, T1?>.getValue(key: Class<T1>): T1? defined in kotlin.collections
@JvmName @InlineOnly public operator inline fun <V> MutableMap<in String, in T1?>.getValue(thisRef: Any?, property: KProperty<*>): T1? defined in kotlin.collections
Error:(75, 20) Kotlin: Expression in a class literal has a nullable type 'T1?', use !! to make the type non-nullable
Error:(75, 35) Kotlin: Type parameter bound for T in val <T : Any> KClass<T>.memberProperties: Collection<KProperty1<T, *>>
 is not satisfied: inferred type CapturedTypeConstructor(out T1?) is not a subtype of Any

open class Base<T1, T2> (@Autowired var t2: T2) {

    @Autowired var request: T1? = null

  inline fun <reified T1: Any> retrieveClass(): T1? {
    return request.getValue(T1::class.java)
  }

  fun endpoint(
    @ApiParam(value = "Options", required = true) @Valid @RequestBody
        body: T1
    ): ResponseEntity<MyResponse> {
        type1 = body
        val obj = retrieveClass()
        for (prop in obj::class.memberProperties) {
           println("${prop.name} = ${prop.get(obj)}")
        }
        val usefulResult = obj.usefulMethod()
    }
}





C# runtime introspection on Tuple

In my C# application, I need to display a Tuple to users. The problem is that the Tuple could be of any form, and I don't know at compile time what the Tuple will look like, so I have to introspect on it at runtime to display it. The first problem is to identify the type of each component in the tuple, and the second is to get the value of each component.

Getting the value of each component seems to involve Item1, Item2, and so on, but is there a way to get at Items by index? Currently my code is really clunky because I have to use the number of components to decide how may items to iterate through (see below). The bigger problem is however, how to get at the elements because I don't know how to get the Tuple object. The following code compiles, but at runtime the cast of the object to Tuple throws an error of this form:

Unable to cast object of type 'System.Tuple2[System.String,System.Byte[]]' to type 'System.Tuple2[System.Object,System.Object]'.

It looks like the cast fails (I think I understand why), but I don't know how to rewrite the cast to get around this. I have tried things like:

object rowObject = ((Tuple<tupleTypeArray[0], tupleTypeArray[1]>)object).Item1;

but this does not compile. Help would be appreciated!

object = SomeTupleGotFromMethodCall();
Type tupleType = object.GetType();
Type[] tupleTypeArray = tupleType.GenericTypeArguments;
int tupleLength = tupleType.GenericTypeArguments.Count<Type>();
for (int i = 0; i < tupleLength; i++)
{
    if (tupleLength == 1)
    {
        if (i == 0)
        {
            Type firstType = tupleTypeArray[0];
            object rowObject = ((Tuple<object>)object).Item1;
            if (rowObject != null)
            {
                display(rowObject);
            }
        }
    }

    if (tupleLength == 2)
    {
        if (i == 0)
        {
            object rowObject = ((Tuple<object, object>)object).Item1;
            if (rowObject != null)
            {
                display(rowObject);
            }
        }

        if (i == 1)
        {
            object rowObject = ((Tuple<object, object>)object).Item2;
            display(rowObject);
        }
    }

    ...
}





Java 9 dependency issues regarding serviceloader

I have a question about how the serviceloader changed in Java 9 based on this scenario


Scenario

Project gert Class Main

package gert;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class Main { 
    static public void test() throws JAXBException {
        InputStream is = new ByteArrayInputStream("<Classes RUNTIME_INCLUDE_JARS=\"\"><Class></Class></Classes>".getBytes(StandardCharsets.UTF_8)); 
        JAXBContext jaxbContext = JAXBContext.newInstance(ClassesDef.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.unmarshal(is);
    }
}

Project gert Class ClassesDef

package gert;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="Classes")
public class ClassesDef {
    @XmlAttribute(name="RUNTIME_INCLUDE_JARS")
    public String jars=null;

    @XmlElement(name="Class")
    public String classes;
}

Project gert pom.xml

<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
    <modelVersion>4.0.0</modelVersion>
    <groupId>gert</groupId>
    <artifactId>gert</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>gert.Main</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency><!-- org.eclipse.persistence.jaxb.JAXBContextFactory comes with this dependency-->
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>2.26</version>
        </dependency>
    </dependencies>
</project>

Project cristina Class Main

package cristina;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {
        System.setProperty("javax.xml.bind.JAXBContextFactory", "org.eclipse.persistence.jaxb.JAXBContextFactory");
        String bWithDep = "C:\\Users\\gert\\eclipse-workspace91java\\gert\\target\\gert-0.0.1-SNAPSHOT-jar-with-dependencies.jar";
        List<URL> jars = new java.util.ArrayList<URL>();
        File f;
        f = new File(bWithDep);
        jars.add(f.toURL());
        URL[] urls = (URL[])jars.toArray(new URL[jars.size()]);
        URLClassLoader urlloader = URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
        System.out.println("Before\tgert.Main.test();.");
        Class<?> c= Class.forName("gert.Main", true, urlloader);
        Object gert = c.newInstance();
        Method m = c.getMethod("test");
        m.invoke(gert);
        System.out.println("After\tgert.Main.test();.");
    }
}

Project cristina pom.xml

<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU" xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/VE5zRx">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cristina</groupId>
  <artifactId>cristina</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <!-- <dependency>
      <groupId>javax.xml.bind</groupId>
         <artifactId>jaxb-api</artifactId>
         <version>2.3.0</version>
      </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-moxy</artifactId>
        <version>2.26</version>
    </dependency> -->
  </dependencies>
</project>

So the cristina main loads the gert project and executes a method of gert named test()

Testing

Java 8
When the project is run with java 8 it works

Command

"C:\Program Files\Java\jre1.8.0_151\bin\java.exe" -cp C:\Users\gert\eclipse-workspace91java\cristina\target\cristina-0.0.1-SNAPSHOT.jar cristina.Main

Output

Before gert.Main.test();. After gert.Main.test();.
Java 9
When the same is done with java 9 it doesnt

Command

"C:\Program Files\Java\jre-9.0.1\bin\java.exe" -cp C:\Users\gert\eclipse-workspace91java\cristina\target\cristina-0.0.1-SNAPSHOT.jar cristina.Main

Output

Before  gert.Main.test();.
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at http://ift.tt/2tn7UHR(Native Method)
        at http://ift.tt/2xHLRk5(Unknown Source)
        at http://ift.tt/2kgGdjs(Unknown Source)
        at http://ift.tt/2wE83Yn(Unknown Source)
        at cristina.Main.main(Main.java:23)
Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
 - with linked exception:
[java.lang.ClassNotFoundException: org.eclipse.persistence.jaxb.JAXBContextFactory]
        at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:278)
        at javax.xml.bind.ContextFinder.find(ContextFinder.java:397)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
        at gert.Main.test(Main.java:14)
        ... 5 more
Caused by: java.lang.ClassNotFoundException: org.eclipse.persistence.jaxb.JAXBContextFactory
        at http://ift.tt/2itv8uy(Unknown Source)
        at http://ift.tt/2z2MOVc(Unknown Source)
        at http://ift.tt/2z62oMq(Unknown Source)
        at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
        at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
        at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:276)
        ... 9 more

The 2 above are done directly from the command line.
BUT
When I uncomment the dependencies in the pom.xml of the cristina project and I do a maven install and run the project from eclipse, java 9 works. So it seems that eclipse also takes the maven dependencies into consideration when running a project.

Question

When the dependencies are in the gert project and only used by the gert project why does the cristina project throw an exception when running it with Java 9?





Reflection vs public method

While I've learned/studied reflection in the past, I never really dove into use cases (and I'm honestly not sure I'm understanding it's value now either). However, while working on a problem for a personal project, I asked a coworker for thoughts on a problem I was stuck on and he suggested reflection. After some review and doc reading, it got me thinking:

The core of my problem is a property that is protected static, and thus can't be accessed outside the class. However, it's turning out I need access to it and while a user of the package would never need to use a method I setup to get the property, I also don't see why I should give them access to the data directly as such. It makes it seem that reflection is a good pattern to follow here, to allow access to the property through the Reflection class, but at the same time, it makes me wonder about just making a public getter for the field.

Am I looking at reflection wrong? From a number of examples I've seen online, I wonder why use reflection instead of making getters? Is it a PHP thing, where other languages (specially typed languages) can use reflection more usefully?





Ignoring exception checking while using Method.invoke in java

In a project I am taking part in, there is a plethora of classes each implementing a method called add which all work the same way, e.g. MyVector sum = add(vector1, vector2), where vector1 and vector2 are both of type MyVector. I have no permission to modify of all the classes that have add, so I could have make them implement some interface "IAddable".

Now, I'd like to make a generic class of the form

class Summinator<TVector>
{
    Function<TVector,TVector,TVector> add;

    public Summinator()
    {
        //... somehow get the class of TVector, say cVector
        Method addMethod = cVector.getDeclaredMethod("add", new Class[] {cVector, cVector});
        add = (v1, v2) -> (TVector)addMethod.Invoke(null, v1, v2);
    }

    public TVector VeryLargeSum(TVector[] hugePileOfVectors)
    {
        TVector sum = hugePileOfVectors[0];
        for (int i = 1; i < hugePileOfVectors.length; i++)
        {
            sum = add(sum, hugePileOfVectors[i]);
        }
        return sum;
    }
}

As the sum is large, I'd like to have a lambda-expression to do the work. I also make type-checking at the initiation time. However, java wants me check for exceptions every time I invoke the method, so instead of

add = (v1, v2) -> (TVector)addMethod.Invoke(null, v1, v2);

it forces me to write something like

add = (v1, v2) -> 
{
    try {
    return add.invoke(null, v1, v2);
    } catch (IllegalAccessException e) {
         e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
};

I am afraid that this exception-checking will consume lots of machine time, whereas all the objects are in fact quite basic in their nature and the application of add is in fact a matter of a handful of flops. If it was C# and all classes in question had an overloaded + operation, I could have solved my problem with System.Linq.Expressions package, using the supported binary operations: there exception checking is not obligatory. But... I am to work in java.

Perhaps, there is some way around to at least ignore exception checking?





C# : Create a Tuple from a generic type using reflection

I would like to be able to pass a Tuple to the following method, however I can't since I have to instantiate it.

    public List<T> SelectFromDataBase<T>() where T : new()
    {
        var ls = new List<T>();

        // highly simplified here
        T t = new T();
        t.GetType().GetProperty("ClientName").SetValue(t, "Mr Smith");

        ls.Add(t);

        return ls;
    }

Is there any solution ?





mardi 21 novembre 2017

How can I find the file extension of the currently running code?

MATLAB provides the mfilename function. It returns the name of the file where the function was invoked, but unfortunately, it returns the file name without the extension.

So for example, if we have a file called myfile.m and we call mfilename inside the file, it will return the string 'myfile' but not 'myfile.m'

I also had a look at the fileparts function but it is not useful either because it only parses the string that you provide.

I am developing a piece of code has a different behavior based on the file extension. So for instance, it needs to know whether the extension of the file is .m or .p at run time.

You can check the list of extensions associated with MATLAB here.

How can I do it?





Reflection code gets error in .NetStandard or .NetFramework

I have forked HtmlAgilityPack to my github and clone it to my visual studio.

The project

The HtmlAgilityPack targets .NetFramework 2.0 and HtmlAgilityPack.NetStandard targets .NetStandard 1.6

I added some reflection codes to it , for example :

public static PropertyInfo GetFirstPropertyInfo(Type t)
{       
     return t.GetProperties().First();
}

It gets me this error :

'Type' does not contain a definition for 'GetProperties' and no extension method 'GetProperties' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?) HtmlAgilityPack.NETStandard

After some StackOverflowing I found out I should use this code instead :

public static PropertyInfo GetFirstPropertyInfo(Type t)
{       
     return t.GetTypeInfo().GetProperties().First();
}

but this code gets error in .NetFramework !

'Type' does not contain a definition for 'GetTypeInfo' and no extension method 'GetTypeInfo' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?) HtmlAgilityPack

What should I do ???

Thanks.





C# Construct a default object for a Tuple by reflection

In my C# application, I have the need to create an instance of a Tuple. But here's the catch - I don't know the Tuple type in advance, only at runtime. If I have methods that can create instances of any types likely to be in the Tuple, then is there a way to use reflection to create such a Tuple instance? For example, I'm thinking along these lines, but I can't get it to work:

if (type typeof(Tuple))
{
    FieldInfo[] fieldInfoArray = type.GetFields();
    object[] = CreateArrayOfObjectsFromFieldInfoArray(fieldInfoArray);
    return new Tuple(objectArray);
}

Is there a better way to do this?





parameterizing a python object with a generic factory

I am trying to parametrize my objects with a json string provided at runtime through a rest API. I have come up with the following design. It works, but I feel like using class reflection and setattr are bad programming practices...but I don't know any other way of doing this in the fully generic way I want (I would like to be able to extend classes in the future which have new attributes, register more nested classes, etc)

Is this JUST awful, is there a better way?

class Factory:
    contains = {}

    @staticmethod
    def subclass(this, args):
        klass = next((cls for cls in this.__class__.__subclasses__(this) if cls.__name__ == args.get('type', None)),
                            this.__class__)
        return klass()

    def __init__(self, d=None):
        for key, value in self.contains.items():
            args = d.get(key, None)
            child = self.subclass(value, args)
            setattr(self, key, child)

class Clock(Factory):
    def tick(self):
        print("base clock tick")

class DigitalClock(Clock):
    def tick(self):
        print("digital clock tick")

class House(Factory):
    contains = {'clock': Clock}
    def __init__(self, d):
        self.color = d.get('color','red')
        super().__init__(d)


H = House({'clock': {'type': "DigitalClock"}, 'color': 'blue'})
H.clock.tick()





Conversion from object to List

This question already has an answer here:

I am trying to implement the function public IEnumerable<T> ConvertFrom<T>(object setOfElements, Type sourceType) where T : MyInterface, where:

  • setOfElements is given as an object, but it actually is an HashSet of sourceType
  • sourceType is the original type of source elements
  • T is the output desired type, and it inherits from MyInterface
  • MyInterface contains the method public T BuildFrom(sourceType x), which can be used to map a sourceType object into a T object

In other words, I need to perform something like:

return ((IEnumerable)setOfElements).Cast<sourceType>()
                                   .Select(x => new T().BuildFrom(x))

That line of code works perfectly when I know the types at compile time, but with generic types I need to invoke that using reflection and I can't succeed.

Please consider that my issue is not how to generally call a generic method via reflection, but which parameters/calls to nest to perform that behavior





Reflection - invoke

having the class:

public class TestClass {
    public void testMethod() {
    }

I want to pass it to the below executor method, that should invoke its testMethod method.

public class SimpleUnitTester {
    public int executor(Class clazz) {
        clazzObject = clazz.newInstance();
        for (Method m : clazz.getDeclaredMethods()) {
            m.invoke(clazzObject)); <--
        }
    }
}

But its obviously wrong. What is the correct way?

Thanks!





lundi 20 novembre 2017

lookup java class suitable constructor

what is or will be the faster way to lookup suitable constructor matching object types (find constructor which fits our init args method) for given example:

class A implements IA3,IA2,IA1 {
}

class B implements IB1,IB2 {
}

public class C implements IC1 {

   private static volatile Object _simpleLock =  new Object();

   private static IC1 _instance;
   public static IC1 getInstance() {
       if(getState())  {
           return _instance;
       }
       throw new IllegalStateException("Call make me first :)")
   }

   public static boolean getState() {
      return _instance != null && _instance.isInitialized()
   }

   // this is default C class constructor 
   // but subclass can have its own multiple version
   // (regardless modifiers)
   // and we need to find the best one 
   // which fits to passed arg to init method 
   protected C(IA2 a, IB) {
   }

   //  smart try initialize :) from what we will give you 
   public static <IA extends IA2, IB extends IB1, IC extends IC1> 
      void initialize(Class<IC> forClass, IA a, IB b) {
          synchronize(_simpleLock) {
             try {
                // >>> lookupMatching constructor types ???  <<<
                // 1) getDeclaredConstructors 
                // 2) match each permutation on class
                // and its interfaces (from sub to super?)
                // handling possible null objects?
                Class[] types = 
                // 
                IC constructor = forClass.getDeclaredConstructor(types);
                constructor.setAccessible(true);
                _instance = constructor.newInstance(new Object[]{a,b});  
                _instance.setInitialized(true);
             } catch {Exception e} {
             }
         }
   }
}

usage :

// call 1
C.initialize(C.class, new IA2 {impl}, new IB1 {impl});

// call 2
class IA7 impplements IA2 {
}

C.initialize(C.class, new IA7(bla,bla), new IB1 {impl});

// call 3 
class IA7 impplements IA2 {
}

class IA6 impplements IA2 {
}

class C2 implements IC1 {

       protected C2(IA7 a, IB1 b) {
       }

       protected C2(IA6 a, IB1 b) {
       }
}

C.initialize(C2.class, new IA7(bla,bla), new IB1 {impl});
// or 
C.initialize(C2.class, new IA6(noblabla), new IB1 {impl});





Android/Java Reflection Class.getDeclaredFields() is not retrieving anything

I've been using reflection in android development since last year without any problems. After updating my Android Studio 3.0 I noticed that everything related to Reflection, that was working until then, just stopped working. I am no longer having success when trying to retrieve fields from a class using the method getDeclaredFields(), the result is always an empty array. After searching for almost a week, and trying a lot of different kind of stuff, I tried running a unit test with the code below, and it went well, but when I try to run the same code on an Activity, for example, I got no results, only the same old empty array.

Field[] fields = User.class.getDeclaredFields();
Log.d(HOME_ACITIVITY_TAG, "Count: " + fields.length);
for (Field field : fields)
     Log.d(HOME_ACITIVITY_TAG, "FieldName: " + field.getName());

Is there anyone who knows what is happening? Most of my project are depending on this, I used Reflection for almost everything.

Best Regards





python decorator that calls super init

I'm trying to make a decorator that automatically calls the parent class init. It works with single inheritance but when I try to chain the effect I get a stack overflow error. Can anyone explain (a) Why this is happening and (b) How to accomplish what I want to accomplish?

def init(__init):
    def wrapper(self, *args, **kwargs):
        self.__class__.__bases__[0].__init__(self)
        __init(self)
    return wrapper

class Base:
    def __init__(self):
        print("base init")


class Parent(Base):
    @init
    def __init__(self):
        print("parent init")

class Child(Parent):
    @init
    def __init__(self):
        print("child init")

a = Parent() #works
#c = Child() #stack overflow





Find intersection of two lists by KeyAttribute and property value

I want to get the intersection of two lists by reflection of the KeyAttribute properties values :

This given me the primary key properties (for composite) :

IEnumerable<PropertyInfo> keys = typeof(T).GetProperties().Where(prop => prop.IsDefined(typeof(KeyAttribute)));

Now, how can I find the intersection of two lists ?

private static ICollection<T> Except<T>(this ICollection<T> source, ICollection<T> toIgnore)
{
    IEnumerable<PropertyInfo> keys = typeof(T).GetProperties().Where(prop => prop.IsDefined(typeof(KeyAttribute)));
    return source.Where(x => ???);
}

The final use case I want is : var result = firstList.Except(second); It must return items of the first list who don't match key properties values with the second list.





Sonar Java Use local files of the IDE

I am using sonar.version 6.3 and java.plugin.version 4.12.x and I am currently writing some custom rules to analyze my project java files via SonarQube/SonarLint and I have problems with the following scenario:

My goal is to report all Class.forName("path.to.the.Clazz") occurances in which the Clazz implements a specific interface or has a specific annotation with SonarLint.

So I did the following: I invoked Class.forName("path.to.the.Clazz") and checked whether Clazz meet my reporting requirements via reflection or lambda factory. All tests were passed and maven built the custom plugin.

Lets say I want to detect @Table instances which are created via reflection. When analyzing for example the following

package test;

import javax.persistence.Table;

@Table
class TableT {}


public class ReflectionTest {

    public static void main(String[] args) throws ClassNotFoundException {

        Class<?> aClass = Class.forName("test.TableT");
    }
}

the rule will not detect Class.forName("test.TableT"). This is because when my rule calls Class.forName("test.TableT") the TableT class is not actually found by the ClassLoader which I understand.

So I guess reflection is the wrong approach here.

How can I detect such a scenario?

I would not want to provide the code of test.TableT as a dependency in Maven I rather would want to take it dynamically from the project I analyse with SonarLint in my IDE. I also would want to keep it IDE independent.

Regards,

trin





Selenium: How use FieldDecorator and Locator.ElementHandler with ArrayList?

I have some complex object on a Page and I would like become it from a simple WebElement from Selenium on one better abstraction:

public class MyPage {  

    @FindBy(css="select#testme")  
    public MograblogSelect select;  

    public void changeToOption2(){  
        select.val( "option2" );  
    }  

    public void changeToOption1(){  
        select.val( "option1 ");  

    }  
}

This works like a charm following the post: http://ift.tt/2mJ7uMF

But I don't know how to adapt the FieldDecorator and Locator.ElementHandler for be able they work with an ArrayList:

public class MyPage {  

    @FindBy(css="select#testmelist")  
    public List<MograblogSelect> selects;  

}

In this second case selects.get(0) always returns null. How should I do this?





dimanche 19 novembre 2017

EF string of random numbers in GetType().Name

I am reading entity name from ChangeTracker.Entries().GetType().Name but it has string of random numbers attached to entity name. Is there a way to get correct entity/table name.

Thanks





Iterate over methods in the order as written in the class - java reflection [duplicate]

This question already has an answer here:

i want to iterate over methods in the order as written in the class

for example if this is the class's methods

     public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

i want to retrieve

-getName

-setName

-getId

-setId

this retrieve them randomly

    Method[] methods = i.getClass().getDeclaredMethods();
    for (Method method : methods) {
        System.out.println(method.getName());
    }





String.intern() returning different values in a JDBC driver

Whilst I was trying to make a fake JDBC driver to test a secure classloader I found an odd behaviour with the following code:

val stringClass = java.lang.String::class.java
val intern = stringClass.getMethod("intern")
val pooledString = intern.invoke("Hello World") as String
val valueField = stringClass.getDeclaredField("value")
valueField.isAccessible = true
val pooledValue = valueField.get(pooledString) as ByteArray
println(
        """|----------------------------------------
           | String: ${System.identityHashCode(stringClass)}
           | Thread: ${Thread.currentThread()}
           | Pooled: ${System.identityHashCode(pooledString)}
           | Internal: ${System.identityHashCode(pooledValue)}
           |----------------------------------------""".trimMargin()
)
for (index in pooledValue.indices) {
    pooledValue[index] = 'X'.toByte()
}

Running the above code from a JDBC driver's companion object gives this:

String: 349885916
Thread: Thread[main,5,main]
Pooled: 718231523
Internal: 1349414238

but running the same code from a method of the test class before loading the JDBC driver (during the same execution of the program) gives this:

String: 349885916
Thread: Thread[main,5,main]
Pooled: 1635756693
Internal: 504527234

I would have thought that getting the interned version of the string should have given the same string in both cases, but it seems that even within the same run of the program the 2 locations give different values for String.intern, which conflicts with the javadoc which says:

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

Is this to be expected, and if so why is it that the values differ?





How to make mutable fields of a Java Bean immutable at run time using reflection

I am getting some Java objects from a library which have mutable map objects as fields. I need a way to make those object fields read only at run time by wrapping the map objects in Collections.unmodifiableMap() method. I have tried the below approach using Java Reflection API, but I am stuck at getting the actual map instance from the field:

public static <T>T freeze(T obj){
    if(obj!=null){
        Field[] fields=obj.getClass().getDeclaredFields();
        for(Field field:fields){
            if(field.getType().equals(Map.class)){
                //How to wrap a Map instance from the field in Collections.unmodifiableMap() object
            }
        }
    }
    return obj;
}





Modify collection content using java reflection

Here my case: I code a function which will check for any object in each property (for any deep level) if there is a specific annotation and if yes it'll set the property to null. But I'm facing a problem: how to check if a property is a collection, i'll need to check for each element of the collection if there is the annotation and if yes i remove the object from the collection and set the collection with the new checked collection.

My question: how to modify this collection content using reflection?





Java reflection: Calling methods with different argument dynamically

I am trying to call different methods from a class dynamically.

detFunctions.java:

package detFunctions;

import java.lang.reflect.*;
import java.sql.*;  

public class detFunctions{
    public static void main(String[] args) throws Exception {
    String funcId = "";
    String funcName = "";
    String funcDesc = "";
    String Input = "";
    try{
        System.out.println("Retrieving Function for Execution....");

        Class.forName("oracle.jdbc.driver.OracleDriver");  
        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.168.4:2921:SCRDEV","custom","custom");
        Statement stmt=con.createStatement(); 
        ResultSet rs=stmt.executeQuery("select FUNC_IDENTIFIER,FUNC_NAME,FUNC_DESC from custom.dfmt");
        Input = "10001|10002|10003";
        while(rs.next()){
            funcId = rs.getString("FUNC_IDENTIFIER");
            funcName = rs.getString("FUNC_NAME");
            funcDesc = rs.getString("FUNC_DESC");       
        }   
        con.close();
        System.out.println("Function execution completed!!!");
    } catch (Exception e){ System.out.println(e);} 
    System.out.println(funcId);
    System.out.println(funcName);
    System.out.println(funcDesc);
    System.out.println(Input);

    //Reflection of DETFunctions (Raw Type)
    String classId = "detFunctions.detFuncSet1";
    Class c = Class.forName(classId);
    Method m = c.getDeclaredMethod(funcId, new Class[] {String.class});
    Object i = c.newInstance();
    Object funcOutput = m.invoke(i, Input);
    System.out.println(funcOutput);


    //Reflection of DETFunctions (Generic Type)

  } //End of Main Function
} //End of class

*

detFuncSet1.java:

package detFunctions;

public class detFuncSet1 {

    public double GL_BALANCE(String GLList) {
        System.out.println("GL_BALANCE Method invoked.......");
        double GLBalance = 5005689.50;
        System.out.println("GL_BALANCE Method execution completed.....");
        return GLBalance;
  }

    public double EFF_BALANCE(String AcctNo,String InDate) {
        System.out.println("EFF_BALANCE Method invoked.......");
        double EFFBalance = 500.50;
        System.out.println("EFF_BALANCE Method execution completed.....");
        return EFFBalance;
  }
}

Here I am trying to execute methods from detFuncSet1 class using refection. But getDeclaredMethod is a raw type so I am not able to pass the inputs of different types to the methods.

In the above code, getDeclaredMethod has arguments which is parameter type. Based on the query i am executing I am deriving the funcId (which is my method name). Since my methods (in class detFuncSet1 class) are having different inputs I am not able to pass the parametertype dynamically to getDeclaredMethod. Is there a way i can execute my methods dynamically?





How to pass a function as predicate to another function, When name of the predicate function is received at RunTime?

I receive the name of the function to be used as biPredicate at runtime. I want to pass around this biPredicate and evaluate, basically filter to get results. Following is my utility that defines biPredicates. I tried utilizing MethodHandle and Lambda Functions. When I use

new FilterUtility().execute("genericFilter");

I get java.lang.UnsupportedOperationException: MethodHandle.invokeExact cannot be invoked reflectively

public class FilterUtility {

public void execute(String filterName) throws Throwable {
    ActualBean beanObject = ActualBean.builder().param1("true").param2("false").build();

    MethodType methodType = MethodType.methodType(boolean.class, Object.class, Object.class);
    MethodHandles.Lookup lookup = MethodHandles.lookup();
    MethodHandle handle = lookup.findStatic(FilterUtility.class, filterName, methodType);
    BiPredicate<Object, Object> f = (BiPredicate<Object, Object>) LambdaMetafactory.metafactory(lookup,
            "test",
            MethodType.methodType(BiPredicate.class),
            methodType.generic(),
            handle,
            methodType)
            .getTarget()
            .invokeExact();

    resolve(beanObject, new HashMap<>(), f);
}

public static <SourceObject, TemplateObject> Map<String, String> resolve(SourceObject src,
        TemplateObject template,
        BiPredicate<SourceObject, TemplateObject> p) {
    if (p.test(src, template))
        return new HashMap<>();

    return null;
}

public static <SourceObject, TemplateObject> boolean genericFilter(SourceObject x, TemplateObject y) {
    ObjectMapper ob = new ObjectMapper();
    Map<String, Object> source = ob.convertValue(x, Map.class);
    Map<String, Object> template = ob.convertValue(y, Map.class);

    for (Map.Entry<String, Object> entry : template.entrySet()) {
        if (!source.get(entry.getKey()).equals(entry.getValue()))
            return false;
    }
    return true;
}
}

When I change implementation of execute to following, I dont get exceptions.

public void execute(String filterName) throws Throwable {
    ActualBean beanObject = ActualBean.builder().param1("true").param2("false").build();
    resolve(beanObject, new HashMap<>(), FilterUtility::genericFilter); }

This makes me believe that there is something wrong with the way I am trying to find the function with name and send it as a biPredicate.





samedi 18 novembre 2017

Using reflection to find classes and invoke properly

I have an abstract class called Action which accepts a byte array and represents actions done by the client. I have several actions that are implemented from this class and they contain properties, like so:

[Action(ActionCode.Login)]
public class LoginAction : Action
{
    public string Username { get; private set; }
    public string Password { get; private set; }

    public LoginAction(byte[] data)
        : base(data)
    {
        this.Username = this.ReadMapleString();
        this.Password = this.ReadMapleString();
    }
}

I want to be able to defind a method using the actions like so:

public static void Login(LoginAction action)

So when I receive data from the client I can handle the actions based on the code received. However, I'm not sure how to use reflection to find the method that's associated with the action. I mean, I can find LoginAction using the code under, but I can't find the method that's using LoginAction as a parameter, which is the method I want to invoke.

I want to achieve something like:

public void OnRecieveData(ActionCode code, byte[] data)
{
    // Using the ActionCode, call the specified action handler method.
    // Login(new LoginAction(data));
}

I already know how to find classes that use the ActionCodeAttribute, but I'm not sure how to invoke it:

static IEnumerable<Type> GetTypesWithHelpAttribute(Assembly assembly) {
    foreach(Type type in assembly.GetTypes()) {
        if (type.GetCustomAttributes(typeof(HelpAttribute), true).Length > 0) {
            yield return type;
        }
    }
}





.Net Application getting crashed in production with System.IO.FileNotFoundException

.NetApplication is getting crashed with below stacktrace in one of production server. While digging it over various developer forums, I found that this could be bacause any custom exception thrown by different AppDomain is not getting handled in other AppDomain. But I am confused with this as I have defined the custom exceptions which could be raised.I have defined deserialization constructor also for exception propagation to other AppDomains. Please suggest something.

System.IO.FileNotFoundException: File or assembly name Product, or one of its dependencies, was not found. File name: "Product"

     at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase,
Boolean isStringized, Evidence assemblySecurity, Boolean
throwOnFileNotFound, Assembly locationHint, StackCrawlMark& stackMark)
at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Boolean
stringized, Evidence assemblySecurity, StackCrawlMark& stackMark)
at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence
assemblySecurity, StackCrawlMark& stackMark)
at System.Reflection.Assembly.Load(String assemblyString)
at System.Reflection.MemberInfoSerializationHolder..ctor(SerializationInfo
info, StreamingContext context)
at System.Exception.GetExceptionMethodFromString()
at System.Exception.GetTargetSiteInternal()
at System.Exception.get_TargetSite()
at ID.Components.Exceptions.IDTException.ToString()
at ID.UI.IDTecControls.IDTDialogBox.ShowErrorDialog(String
showOnlyMessage, Exception e, String pluginName, String pluginVersion,
String methodName)
at ITI.Plugins.Side.btnNew_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.onclick(EventArgs e)
at System.Windows.Forms.Button.onclick(EventArgs e)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr
wparam, IntPtr lparam)





vendredi 17 novembre 2017

Date's prototype methods are not enumerable. How to obtain a list of them to iterate?

I want to iterate over the methods of a javascript Date object. The first attempt did not work:

var date = new Date();
for (var key in date) {
    console.log(key);
}

I've tried a few related things -- Object.keys, for example. So far I have not found a way to do it.





c# Deep Copy reflection GetMembers

I am trying to deep copy a complex object

public class Team
{
    public string Id { get; set; }
    Driver driver{ get; set;}
    Driver codriver{ get; set;}
}

public class Driver
{
    Team parentTeam{ get; set;}
    public string DriverId { get; set; }
}

var modifiedTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { ParentTeam = "T1", DriverId = "D2" }, Codriver = new Driver { ParentTeam = "T1", DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { ParentTeam = "T2", DriverId = "D1"} }
};

I want to deep copy the modified lists. Below is the utility that I am using.

    /// <summary>  
/// Utility   
/// </summary>  
public static class DeepCopyUtility
{
    private static string[] _excludedPropertyNames = null;
    private static BindingFlags _memberAccess = (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

    /// <summary>   
    /// Copies the data of one object to another. The target object gets properties of the first.    
    /// Any matching properties (by name) are written to the target.   
    /// </summary>   
    /// <param name="source">The source object to copy from</param> 
    /// <param name="target">The target object to copy to public</param> 
    /// <param name="propertyNames">     </param> 
    public static void DeepCopy<T>(T source, T target, string[] propertyNames = null)
    {
        if (source == null)
        {
            throw new ArgumentNullException("Object is null");
        }
        if (propertyNames != null)
        {
            _excludedPropertyNames = propertyNames;
        }
        CopyObjectData(source, target, new Dictionary<object, object>());
    }

    /// <summary>   
    /// Copies the data of one object to another. The target object gets properties of the first.    
    /// Any matching properties (by name) are written to the target.   
    /// </summary>   
    /// <param name="source">The source object to copy from</param> 
    /// <param name="target">The target object to copy to</param> 
    /// <param name="excludedProperties">A comma delimited list of properties that should not be copied</param> 
    public static void CopyObjectData(object source, object target, Dictionary<object, object> cloned)
    {
        Type type = source.GetType();
        if (target == null && type.IsValueType == false && type != typeof(string))
        {
            if (source.GetType().IsArray)
            {
                target = Activator.CreateInstance(source.GetType().GetElementType());
            }
            else if (source.GetType().IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
            {
                if (typeof(IList).IsAssignableFrom(type))
                {
                    target = (IList)Activator.CreateInstance(type);
                }
                else if (type.IsGenericType)
                {
                    var objectType = type.GetGenericArguments().Single();
                    if (typeof(IList<>).MakeGenericType(objectType).IsAssignableFrom(type) || typeof(ISet<>).MakeGenericType(objectType).IsAssignableFrom(type))
                    {
                        target = Activator.CreateInstance(type);
                    }
                }
            }
            else
            {
                target = Activator.CreateInstance(source.GetType());
            }
        }

        MemberInfo[] miT = target.GetType().GetMembers(_memberAccess);
        foreach (MemberInfo field in miT)
        {
            string name = field.Name;

            // Skip over excluded properties   
            if (_excludedPropertyNames != null && _excludedPropertyNames.Contains(name))
            {
                continue;
            }

            object clone;
            if (cloned.TryGetValue(source, out clone))
            {
                // this object has been cloned earlier, return reference to that clone
                continue;
            }

            if (field.MemberType == MemberTypes.Field)
            {
                FieldInfo sourcefield = source.GetType().GetField(name);
                if (sourcefield == null)
                {
                    continue;
                }

                object sourceValue = sourcefield.GetValue(source);
                ((FieldInfo)field).SetValue(target, sourceValue);
                cloned[target] = sourceValue;
            }
            else if (field.MemberType == MemberTypes.Property)
            {
                PropertyInfo piTarget = field as PropertyInfo;
                PropertyInfo sourceField = source.GetType().GetProperty(name, _memberAccess);
                if (sourceField == null)
                {
                    continue;
                }

                if (piTarget.CanWrite && sourceField.CanRead)
                {

                    if (sourceField.PropertyType.IsArray && piTarget.PropertyType.IsArray)
                    {
                        CopyArray(source, target, piTarget, sourceField, cloned);
                    }
                    else if ((sourceField.PropertyType.IsGenericType && sourceField.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
                             && (piTarget.PropertyType.IsGenericType && piTarget.PropertyType.GetGenericTypeDefinition() == typeof(List<>)))
                    {
                        CopyList(source, target, piTarget, sourceField, cloned);
                    }
                    else
                    {
                        CopySingleData(source, target, piTarget, sourceField, cloned);
                    }
                }
            }
        }
    }

    private static void CopySingleData(object source, object target, PropertyInfo piTarget, PropertyInfo sourceField, Dictionary<object, object> cloned)
    {
        object sourceValue = sourceField.GetValue(source, null);
        object targetValue = piTarget.GetValue(target, null);
        if (sourceValue == null) { return; }

        //instantiate target if needed   
        if (targetValue == null && piTarget.PropertyType.IsValueType == false && piTarget.PropertyType != typeof(string))
        {
            if (piTarget.PropertyType.IsArray)
            {
                targetValue = Activator.CreateInstance(piTarget.PropertyType.GetElementType());
            }
            else
            {
                targetValue = Activator.CreateInstance(piTarget.PropertyType);
            }
        }

        if (piTarget.PropertyType.IsValueType == false && piTarget.PropertyType != typeof(string))
        {
            CopyObjectData(sourceValue, targetValue, cloned);
            piTarget.SetValue(target, targetValue, null);
        }
        else
        {
            if (piTarget.PropertyType.FullName == sourceField.PropertyType.FullName)
            {
                object tempSourceValue = sourceField.GetValue(source, null);
                piTarget.SetValue(target, tempSourceValue, null);
                cloned[target] = tempSourceValue;
            }
            else
            {
                CopyObjectData(piTarget, target, cloned);
            }
        }
    }

    private static void CopyArray(object source, object target, PropertyInfo piTarget, PropertyInfo sourceField, Dictionary<object, object> cloned)
    {
        object sourceValue = sourceField.GetValue(source, null);
        if (sourceValue == null) { return; }

        int sourceLength = (int)sourceValue.GetType().InvokeMember("Length", BindingFlags.GetProperty, null, sourceValue, null);
        Array targetArray = Array.CreateInstance(piTarget.PropertyType.GetElementType(), sourceLength);
        Array array = (Array)sourceField.GetValue(source, null);

        for (int i = 0; i < array.Length; i++)
        {
            object o = array.GetValue(i);
            object tempTarget = Activator.CreateInstance(piTarget.PropertyType.GetElementType());
            CopyObjectData(o, tempTarget, cloned);
            targetArray.SetValue(tempTarget, i);
        }
        piTarget.SetValue(target, targetArray, null);
        cloned[target] = targetArray;
    }

    private static void CopyList(object source, object target, PropertyInfo piTarget, PropertyInfo sourceField, Dictionary<object, object> cloned)
    {
        var sourceValue = ((IEnumerable)sourceField.GetValue(source, null)).Cast<object>().ToList();
        if (!sourceValue.Any()) { return; }

        int sourceLength = (int)sourceValue.GetType().GetProperty("Count").GetValue(sourceValue);
        var listType = typeof(List<>);
        Type[] genericArgs = sourceField.PropertyType.GetGenericArguments();
        var concreteType = listType.MakeGenericType(genericArgs);
        var newList = (IList)Activator.CreateInstance(concreteType);

        var obj = (IList)sourceField.GetValue(source, null);
        for (int i = 0; i < sourceLength; i++)
        {
            object[] ind = { i };
            object o = obj[i];
            object tempTarget = Activator.CreateInstance(piTarget.PropertyType.GetGenericArguments()[0]);
            CopyObjectData(o, tempTarget, cloned);
            newList.Insert(i, tempTarget);
        }
        piTarget.SetValue(target, newList, null);
        cloned[target] = newList;
    }

On execution I am getting "System.Reflection.TargetParameterCountException : Parameter count mismatch.". This is mainly because it is trying to get Team value from a list of teams. Can someone help me with how I could fix this.

Note: This utility code is referred from below links:- http://ift.tt/2AWKJYw

http://ift.tt/2yThvZj