vendredi 30 juin 2017

Invoking a static method with java reflection library

I am trying to invoke the following static method through the java reflection library.

import java.net.InetAddress;
import java.net.UnknownHostException;

public class ah
{
  static void a()
  {
    try
    {
      Client.dU = 10;
      Client.dV = 0;
      Client.dX = true;
      cp.d = 32;
      cp.a(InetAddress.getLocalHost());
      Client.iq = Client.E();
      Client.ir = w.a();
      Client.is = 2019030189;
    }
    catch (UnknownHostException localUnknownHostException) {}
  }
}

My current code is as follows

public void invokeInit() throws NoSuchMethodException, SecurityException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Class<?> initClass = loader.loadClass("ah");
        Method initMethod = initClass.getDeclaredMethod("a", null);
        initMethod.invoke(null, new Object[] {});
    }

It gives me the following error

java.lang.IllegalAccessException: Class org.baiocchi.client.reflection.Game can not access a member of class ah with modifiers "static"
    at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
    at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
    at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at org.baiocchi.client.reflection.Game.invokeInit(Game.java:28)
    at org.baiocchi.client.reflection.Game.getApplet(Game.java:33)
    at org.baiocchi.client.Engine.start(Engine.java:21)
    at org.baiocchi.client.Booter.main(Booter.java:6)

Thank you in advance for any help!





Android: Is it possible to download the class (which is an extend of LinearLayout) of an android custom View and instantiate it in runtime?

I'm developing an app which has a thing called widgets(not to be confused with android widgets that you can keep on the desktop)

Widget is an abstract class that extends LinearLayout.

Now we can extend Widget and create various Widgets that do various tasks such as,

AlarmWidget - A Widget that blinks at the time you set
ClockWidget - A Widget that display time.

When I distribute the app it will come with some built in widgets that I have coded in my project including the above 2.

But I want developer community to be able to create custom Widgets like the above 2 that will be hosted in a server and can be downloaded by users.

It is not possible to let a user download all the available Widgets on the server through an update due to the large combined size of all the widgets

So the app will download the required class(an extension of Widget class) from server when necessary and instantiate the View.

Each extension of Widget is a complex object containing many child Views attached to it and its own unique methods and code. (therefore not possible to instantiate the class by transferring only information like color,text,backgroundimage etc)

How do I do this?





Can i use Reflection to break limit on AES encryption limit in my banking project?

Can I use Reflection (as below) to break limit on encryption limit in my banking project? What could be the side effects of putting this code inside a single class?

static {
    try {
        Field field = Class.forName("javax.crypto.JceSecurity")
                           .getDeclaredField("isRestricted");
        field.setAccessible(true);
        field.set(null, java.lang.Boolean.FALSE);
    } catch (Exception ex) {
    }
}





Invoking generic method with default datetime parameter through reflection

I have simple generic method with following signature:

public static T SafeGetValue<T>(this XElement xElem, string attrName, 
                                 T defaultValue = default(T), bool throwExceptions = false)

Which I want to invoke like that:

var genericMethod = typeof(XElementExtensions).GetMethod("SafeGetValue");
genericMethod = genericMethod.MakeGenericMethod(type);
genericMethod.Invoke(null,new[] { xElem, "attr", Type.Missing, Type.Missing });

type variable is supplied and it is meant to be different for different invocations (typeof(int), typeof(bool), typeof(string) and etc.. ) , but when I supply it with DateTime, I got runtime exception:

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code.Additional information: Encountered an invalid type for a default value.





Create a new instance of a generic type at runtime without type checking

The following design is simply a template to show my problem.

public interface IHero
{
    string Name { get; }
    int Level { get; }
}
public interface IWarlock : IHero
{
    string MagicType { get; }
}
public interface IKnight : IHero
{
    string CommandHierarchy { get; } 
}
public class Warlock : IWarlock, IHero
{

    string IWarlock.MagicType { get { throw new NotImplementedException(); } }

    string IHero.Name { get { throw new NotImplementedException(); } }

    int IHero.Level { get { throw new NotImplementedException(); } }

    public Warlock(string name, int level, string magicType)
    {

    }
}
public class Knight : IKnight, IHero
{

    string IKnight.CommandHierarchy { get { throw new NotImplementedException(); } }

    string IHero.Name { get { throw new NotImplementedException(); } }

    int IHero.Level { get { throw new NotImplementedException(); } }

    public Knight(string name, int level, string commandHierarchy)
    {

    }
}
public class NullHero : IHero
{

    public string Name { get { return string.Empty } }

    public int Level { get { return -1; } }
}

class Program
{
    static void Main(string[] args)
    {

    }
    //Increments the hero's level.
    static IHero LevelUp(IHero hero)
    {
        if (hero is IWarlock)
            return new Warlock(hero.Name, hero.Level + 1, (hero as IWarlock).MagicType);
        else if (hero is IKnight)
            return new Knight(hero.Name, hero.Level + 1, (hero as IKnight).CommandHierarchy);
        else
            return new NullHero();
    }
}

The problem is that next time I add a new hero, I would have to add another if statement in the LevelUp function and this becomes messy.

I know I can use Activator.CreateInstance to create a new instance however there are two problems, 1. all objects are immutable. 2. number and type of parameters in the constructor.

Could anyone please suggest a solution to this problem?





How to get TypeTag for generic class at runtime

Assume I have one class defined as below

class[T : ClassTag](val x : Int, val y : T) {

}

I have a utility method to use reflection and constructor parameters and create instance

def createInstance[T : ClassTage](cls : Class[_]) {
     val m = universe.runtimeMirror(getClass.getClassLoader)
    val clsSymbol = m.classSymbol(cls)
    val cm = m.reflectClass(clsSymbol)
    val ctorC = clsSymbol.toType.declaration(universe.nme.CONSTRUCTOR).asMethod
    val ctorm = cm.reflectConstructor(ctorC)

    val fullParams = ctorm.symbol.paramss

constructorFullParams.foreach(map => {
      map.foreach(param => {
        val name = param.name.decodedName.toString
        val ptype = param.typeSignature
        if (ptype.toString == "scala.reflect.ClassTag[T]") {
          //dosth()
        } 
      })
    })
}

as you can see above, I just use the type string value to determine whether the type is a ClassTag and then call dosth() method. it doesn't look good though. is there any better way to do the checking ?

thanks.





jeudi 29 juin 2017

Is it possible to inject code into a Java object transmitted over a network through Man In The Middle attack?

In Java, one could do the following to send and receive objects over the network (Without encryption).

class Dog {
    public void bark(){ System.out.println("Woof! Woof!"); }
}

Client.java

Dog fido = new Dog();
Socket socket = new Socket(new InetSocketAddress("192.168.1.2"), 1234);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(fido);
oos.flush();
oos.close();

Server.java

ServerSocket server = new ServerSocket(1234);
Socket client = server.accept();
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
Dog fido = (Dog)ois.readObject();
ois.close();

fido.bark();

My question is, suppose you have successfully established an interception point between two network devices which are sending Java objects back and forth on an unsecured link and that you know their protocol and can modify their data, is it possible to inject Java byte code into the objects to change their behavior?

In our little example, is it possible to make fido "moo!" instead of barking?





Looking for a generic way to display and edit a POJO through a JTable

Short version:

.json ==> treeNode.userObject (general case) ==> editable JTable ==> save back to .json

long version:

I've been working on an editor to create the objects I will be using in a text-based game engine. The way the program works is to display a tree of JSON objects in a directory, and by selecting one display it's properties in a JTable. I already had it working with objects that I coded separate table models for, and populated each row with a specific field from that object, but want to implement a more flexible system of displaying and editing a POJO through a JTable.

I want to be able to edit the number/types of fields an object has in its .class file and not have to add new code to the relevant table model. Ideally I want to have just one table model that displays the selected object's fields by name and value, edits the object's fields when a cell changes value, and can display whatever other object the user selects from the JTree.

My old method required each class to have its own table model with a method that set every cell in the second column to the corresponding value. I want a table model that can acheive the same functionality dynamically for any object passed to it.

My latest attempt has been using reflection, and I can display the object, but am having difficulty figuring out how to get the info back from the table into the object to save as a .json again. Also I've seen lots of warnings about using reflection as it's harder to debug?

question:

Is reflection the best route to go for this, and if so what are some good resources for learning how to do what I'm trying to do? If not, what are some other methods that would work? Would my best bet be to stick to hardcoding the rows and tablemodels for each .class?

Also, I was trying to keep this whole question more general, but if you want me to provide some code for a (maybe?) better idea of what I'm trying to acheive, just let me know and I can get some "tidy" example in.





Java Reflection NoSuchMethodException when referencing a method in same class

I am experiencing a NoSuchMethodException when trying to call getMethod on a method in the same class with no arguments from a string name pulled from a hashmap. Any advice? The call to get the method is here:

if (testChoices.containsKey(K)) {
        String method = testChoices.get(K);
        System.out.println(method);

        try {
            java.lang.reflect.Method m = TST.getClass().getMethod(method);
            m.invoke(testChoices.getClass());
        } catch (NoSuchMethodException e1) {
            // TODO Auto-generated catch block
            System.out.println("No method found");
            e1.printStackTrace();
        } catch (SecurityException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();


        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

One of the methods I am trying to call is here:

private static void testgetDomainLic() throws IOException {

And the map entry being called is here:

testChoices.put(1, "testgetDomainLic");





Scala Reflect Case Class Apply Method Runtime

How do you reflect a case class's members at run time without an instance?

For example if I have the following case class:

package com.abc

object Holder {
  case class Hello(message:String,count:Int)
}

I would of thought although I don't have an instance of Hello to reflect I could reflect the Companion Object apply method and inspect the arguments to know about what members it has?

val mirror = ru.runtimeMirror(getClass.getClassLoader)
val module = mirror.staticModule("com.abc.Holder$Hello")
val instance = mirror.reflectModule(module).symbol.typeSignature.member(TermName("apply")).asMethod.paramLists
instance.foreach(println)

However this returns "none" is not a method. So it doesn't have an apply method?





Fix PrivilegeEscalation in java code

I am scanning my project using IBM AppScan tool. It returning PrivilegeEscalation error. I am not able to find the solution.

The error showing the below two lines

String value1 = method.invoke(class.cast(object1)).toString(); String value2 = method.invoke(class.cast(object2)).toString();

Java Code:

import java.util.Comparator;
import java.lang.reflect.Method
public class TestComparator implements Comparator {

private Class class;
 public TestComparator(Class class,String methodName){
    this.class = class;
    this.methodName = methodName;
}

public int compare(Object object1, Object object2) {
    try{
        Method method =class.getMethod(("get"+methodName));
        String value1 = method.invoke(class.cast(object1)).toString();
        String value2 = method.invoke(class.cast(object2)).toString();
        return value2.compareTo(value1);
    }catch(Exception ex){
        //  ex.printStackTrace();
    }
    return 0;
}}





Can someone point me to a good c# reflection cheat sheet?

I failed to find any "classic" cheat sheat, only partly explained stuff outside of msdn.

Thanks!





Scala newInstance() an inner class nested in a trait

I'm using java reflection in order to dynamically instantiate all the classes sharing the same trait in the codebase. It's working currently if thoses classes do not belong to a super class.

So basically in order to instantiate Y :

class X {
  class Y {

  }
}

I have to use YConstructor.newInstance(XObject)

The problem arise when X is no more a class but a trait, and then there is no constructor that I can use for it, but I still need to feed an XObject to newInstance .. Tricky :(





mercredi 28 juin 2017

Is using the isInstance method on a static field shared between threads safe?

I'm working on a program where due to various reasons I only know the name of the class I need at runtime, so I have to use reflection to access it. In one particular place in my program I have to check whether an object is an instance of that class, and as I'm using reflection I can't use instanceof.

I am storing the object representing the class in a final static field and I am checking if other objects are instances of that class using MY_CLASS.isInstance(obj).

However, now I also need to run this check in concurrent manner, meaning that more threads will have access to the MY_CLASS field. Given that I don't understand exactly how the isInstance method operates (and I don't think it works the exact same way as instanceof), I want to know whether this approach is safe to use.

Thank you!





Reflection java

I have to retrieve a function "a" in this object but I dont know how to do

    public static final DataWatcherSerializer<Float> c = new DataWatcherSerializer<Float>(){

    @Override
    public void a(PacketDataSerializer packetDataSerializer, Float f2) {
        packetDataSerializer.writeFloat(f2.floatValue());
    }

    public Float b(PacketDataSerializer packetDataSerializer) {
        return Float.valueOf(packetDataSerializer.readFloat());
    }

    @Override //here
    public DataWatcherObject<Float> a(int n) {
        return new DataWatcherObject<Float>(n, this);
    }

    @Override
    public Float a(Float f2) {
        return f2;
    }

    @Override
    public /* synthetic */ Object a(PacketDataSerializer packetDataSerializer) {
        return this.b(packetDataSerializer);
    }
};

Thank you for reading my question





How do I get the properties of a class that don't contain an attribute at runtime

So I have an Attribute I have created like so:

public class IgnoreFilter : Attribute
{
}

and I have a class that I have used it on also like so:

public class Customer
{

    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            RaisePropertyChanged();
        }
    }

    private string address;
    [IgnoreFilter]
    public string Address
    {
        get { return address; }
        set
        {
            address = value;
            RaisePropertyChanged();
        }
    }

I am now trying to get all of the properties at runtime from my Customer class that do not contain the IgnoreFilter attribute. So far I have...

customer.GetType().GetRuntimeProperties().Where(p => !p.CustomAttributes.Contains(typeof(IgnoreFilter)));

But the last line doesnt compile. I think I am on the right lines but I am probably missing something.

Can someone help get properties from a class that do not contain a custom attribute?





Reflection of hide interface

How can i call registerAudioPortUpdateListener?
I succeeded to call a hidden function.
But, in this situation i need to call a function with hidden inner interface as parameter.

public class AudioManager {
    /**
     * Listener registered by client to be notified upon new audio port connections,
     * disconnections or attributes update.
     * @hide
     */
    public interface OnAudioPortUpdateListener {
        /**
         * Callback method called upon audio port list update.
         * @param portList the updated list of audio ports
         */
        public void onAudioPortListUpdate(AudioPort[] portList);

        /**
         * Callback method called upon audio patch list update.
         * @param patchList the updated list of audio patches
         */
        public void onAudioPatchListUpdate(AudioPatch[] patchList);

        /**
         * Callback method called when the mediaserver dies
         */
        public void onServiceDied();
    }


    /**
     * Register an audio port list update listener.
     * @hide
     */
    public void registerAudioPortUpdateListener(OnAudioPortUpdateListener l) {
        sAudioPortEventHandler.init();
        sAudioPortEventHandler.registerListener(l);
    }
}





mardi 27 juin 2017

getting the "pointer" to NavigationBarView.java by reflection

I am using an old phone and trying to change few things programatically on the navigation bar. I narrowed down to the class that handles the navigation bar which is below.

http://ift.tt/2sP1ov3

the object seems to be declared here:

http://ift.tt/2sk9rwA

line 238

private NavigationBarView mNavigationBarView = null;

Is there a way to get the pointer to this object programatically? The only thing I can find is code to get the bigger container like when you hide the navigation bar programatically.

        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        decorView.setSystemUiVisibility(uiOptions);

yet, this is not enough. I want to drill down to the navbar drawables.

any clues are greatly appreciated.

thank you.





Create method dynamically, including dynamic but fixed argument list, with define_method in ruby?

How do I create a method dynamically with a fixed list of arguments determined at runtime by an array of symbols, or a fixed hash of named parameters?

Statically, I write

 def foo(bar,baz)
   [bar,baz]
 end

 foo(1,2) #=>[1,2]
 foo(1,2,3) #=> ArgumentError: wrong number of arguments (given 3, expected 2)

Now I want to create this method at runtime. According to define_method: How to dynamically create methods with arguments we can just

 define_method(:foo) do |bar,baz|
   [bar,baz]
 end

 foo(1,2) #=> [1,2]
 foo(1,2,3) #=> ArgumentError: wrong number of arguments (given 3, expected 2)

But that only works if I know the argument list when writing the method. What if only have the argument list at runtime? At How do you pass arguments to define_method? it is suggested we can use the splat operator to accept any array of arguments:

 define_method(:foo) do |*args|
   args
 end

 foo(1,2) #=> [1,2]
 foo(1,2,3) #=> [1,2,3]

But can we fix the allowed arguments to conform to a list of arguments given at runtime, duplicate the static code, so that the following happens?

 arr = [:bar,:baz]

 define_method(:foo) do |*args=arr| #or some other magic here
   args
 end

 foo(1,2) #=> [1,2]
 foo(1,2,3) #=> ArgumentError: wrong number of arguments (given 3, expected 2)





What should be resolution of camera that we could fully recover what reflecting in eyes

And when I mean fully, I mean everything in good quantity, enough to recognize letters and faces





DllMain equivalent in C#

I have a managed C# application that loads managed plugins. Depending on a condition I want to be able to run some code on assembly load that will monkey patch the host application to hook some methods.

I tried using module initializers but the .cctor is not called until it tries to reference something in the DLL.

I have seen the answers for C# equivalent of DllMain in C (WinAPI) but none works for me

(this DLL must be a managed DLL; this answer C# equivalent of DllMain in C (WinAPI) won't work as the host application expects to find some managed classes based on an attribute and what I'll have is a native dll.)

Please note that I can not modify the host application.





Customize MS .NET DocumentViewer

If you using MS .NET DocumentViewer and you want customize Find field. For example, instead of "Type text to find..." let put "Words finder" and remove search options (kashida etc). So we get: enter image description here

The answer is below!





lundi 26 juin 2017

ServiceCollection configuration using strings (config files) in .NET Core

Is there a way to configure dependency injection in the standard Microsoft.Extensions.DependencyInjection.ServiceCollection library in .net core, without actually having a reference to the implementation classes in question? (to get implementation class names from configuration files?)

For example:

services.AddTransient<ISomething>("The.Actual.Thing");// Where The.Actual.Thing is a concrete class





Reflections error: java.lang.IllegalArgumentException: wrong number of arguments

I'm developing a RESTfull web application and I keep getting a IllegalArgumentException on this piece of code:

@GET
@Path("/{parent}/subjects/{title}/comments")
@Produces(MediaType.APPLICATION_JSON)
public Collection<Comment> getSubjectComments(@PathParam("parent") String 
  parent, @PathParam("title") String title){

    Subject s = null;
    try {
        s = Database.getSubject(URLDecoder.decode(parent, "UTF-
  8"),URLDecoder.decode(title, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if(s!=null){
        return s.getComments();
    }

    return null;
}

What I'm trying to do is get all the comments associated with the Subject s (each subjects has its own ArrayList of comments and that is what is the return value of s.getComments() )

I checked, all argument and variable values are in order.

I believe the main problem has something to do with reflection, but I can't really figure it out.

This is the ajax code that calls the method:

var parentContainer;
function renderComments(){

var currForum = getCookie("forum");
var currSubject = getCookie("subject");

if(parentContainer==null){
    $.ajax({
        url: "/WebApp/app/forums/"+encodeURI(currForum)+"/subjects/"+encodeURI(currSubject)+"/comments",
        type: "GET",
        dataType: "json",

        success: function(data){
            //javascript code
        }
    });
}else{
    $.ajax({
        url: "/WebApp/app/forums/"+encodeURI(currForum)+"/subjects/"+encodeURI(currSubject)+"/comments/"+encodeURI(parentContainer.id)+"/comments",
        type: "GET",
        dataType: "json",

        success: function(data){
            //javascript code
        }
    });
}

}

When the $.ajax call is made, it never enters the success function.

I'm developing the app with Jersey, on Tomcat 7 server, Eclipse.

Thanks in advance.





how to update all the fields with specific value in a list of object

I have a list of an object, I want to update all the fields that are null to string.empty.

here is the code:

public class Class1
{
    public string P1 { get; set; }
    public string P2 { get; set; }
    public string P3 { get; set; }
}

I want to have a code which goes and find all the null values in all the fields and change the value to string.empty

     static void Main(string[] args)
    {

        var list= new List<Class1>();
        var class1 = new Class1 {P1 = "P1-1", P2 = "P2-1", P3="null"};
        list.Add(class1);
        var class2 = new Class1 { P1 = "P1-2", P2 = "P2-2", P3 = "null" };
        list.Add(class2);

    }

so I would need the class1.P3 and class2.P3 to be found and their value to be replaced.

Thanks





How to convert primitive long datatype to Class type for Class.getMethod(methodName, Class...);

How can i pass a datatype of type long as a param for method which is accepting arbitrary param Class...

I am actually trying to get the reflection of a method from the below class.

 Class Fun(){public Object getBox(long boxId, String boxName){}}

Trying to access this method using below Code.

Class clazz = new fun().getClass(); String str = "Welcome"; Method method = clazz.getMethod("getBox",new Long(22).getClass, str.getClass());

Iam getting the below exception when i try accessing the method name for invoking.

java.lang.NoSuchMethodException:

How to pass a long and a string variable for parametertypes in the below method signature.

public Method getMethod(String name,
               Class<?>... parameterTypes)
                 throws NoSuchMethodException,
                        SecurityException





Loading constants in a different AppDomain

I want to load some constants of an assembly without loading it in my principal AppDomain.

Original code was :

Assembly = Assembly.Load("MyAssembly");
Type myType = assembly.GetType("MyType");
object o = myType.GetType().GetProperty("myProperty").GetValue(null, null);

Knowing that myProperty is initialized with a constant. I can either access it by the property or the constant.

The Type isn't marked serializable (and I can remove the static but nothing more) so I cannot access it by AppDomain.CreateInstanceAndUnwrap but that's precisely what I want to do : loading the constant without getting the assembly to fill my AppDomain.

How can I do that ?





Java How to measure memory consumption for every method reflectivey

In my project I'm loading classes from JAR file and then reflectively i load methods.

What I'm trying to do is to measure or estimate memory usage for picked method. Should I invoke method and use runtime.totalMemory() - runtime.freeMemory() ? Or maybe there is other way to mesure/estimate memory usage. In addition I want to measure heap and stack memory usage.

But how should i make this working for every given method from JAR file ?





Get reference to Class from another class loader at runtime in JAVA

I am running some domain specific scripts in a new thread of an application. The classloader in the thread only has all the classes of the application.

The application also has a module that loads additional classes in jars in a folder at runtime (classes created outside of the application), providing additional functionalities to other parts of the application.

Unfortunately, these two classloaders are not merged and when running my scripts I cannot load any class that I know is there in one of the external jars.

Tried this.getClass().getClassLoader().loadClass("external.cls") no go. Also tried Reflections reflections = new Reflections("external.cls") also no go.

Is there a way to gain access to those classes in my script running thread at runtime? Something like:

  • Gain access to another class loader that loaded the external class?
  • Use reflection to get the external class from the two class loaders?
  • Load the external jars again in my script running thread?




dimanche 25 juin 2017

Java How to estimate how much memory method needs, reflectively from JAR file [duplicate]

This question already has an answer here:

I need to estimate how much memory method needs for execution. I load refletively classes from JAR file and then take specific method from class. But I don't know how to estimate this. Is there any way to do this ?

Extra I need estimate how much stack and heap memory method needs for execution.





How to Use An Objects getClass() Method to set a generic type

Please take look at example code below:

Object o1= new Integer(4); 
ArrayList<Integer> list=new ArrayList<>();
list.add((Integer) o1);

Instead I'd Like to do something like:

Object o1= new Integer(4); 
ArrayList<o1.getClass().getSimpleName()> list=new ArrayList<>();
list.add((o1.getClass().getSimpleName()) o1);

o1.getClass().getSimpleName() returns "Integer" as a Java.lang.String object, my question is how can I embed this string into my code some how with reflection so the type of items in list can be determined at runtime. It is possible to do so by switch statement like:

Object o1= new Integer(4); 
switch(o1.getClass().getSimpleName()){
case "Integer":    
    ArrayList<Integer> list=new ArrayList<>();
    list.add((Integer) o1);
case "String":
    ...

.
.
.
}

but I hope there will be a better solution.





How to implement constraint that a type parameter is a parameterized type

I'd like to make a program that from a FileDialog takes a .class (or maybe a .java file) file on the condition that the class is a generic type, such as LinkedList<T>, ArrayList<T>, or whatever data structure the user selects. I would like to throw an exception if the class is not a generic type. For further explanation, I would like to test if

inputClassX instanceof ParameterizedType

but because I would like to test any arbitrary class that may not implement ParameterizedType, I cannot do that test.

How would I test if an object, or a Class, is a generic type?





Cache computation result of a method in JAVA on a complex object

I'm frequently using a time-consuming method from a vendor library ResultObject complexMethod(ComplexObject obj) and therefore I want to cache the results. The difficulty is that lots of fields in my ComplexObject are involved in the result but also lots of fields are not, so the solution is definitely not to put the ComplexObj as map key. I want to find an easy way to build a key that will include the exact necessary fields. I have come up with the quite tedious idea to create a new method with the minimal arguments and add the arguments until I'm getting the expected results :

   public ResultObject complexMethod(String arg1, int arg2, double arg3, ..., String argN) {
       ComplexObject obj = new ComplexObject();
       obj.setField1(arg1);
        ...
       obj.setFieldN(argN);
       ResultObject result = ComplexClass.complexMethod(obj);
       return result;
   }

But this is not a satisfying solution for me because I want to know the exact fields that are used in the computation.

Is there a correct way to achieve this or any library which does the job ?





Object type and not return type

package enumerations ;   
import java.lang.annotation.Annotation ;

@interface my
{
char c () ;
double d () ;
}

// annotate a class
@my(c='f' , d =34.5 )
class cont implements e
{
int cc  ;   
}
interface e 
{

}

public class annotations4
{
public static void main(String[] args)
{
   cont q = new cont() ;  

   Annotation[] anno = q.getClass().getAnnotations() ; 

    System.out.println(anno.getClass()); 

    System.out.println(anno);  

 // gives  [Ljava.lang.annotation.Annotation;@4e25154f

    e t ;
    t = q ;   
    System.out.println(t);//  gives enumerations.cont@70dea4e

 }
}

I have some confusion here . When I print variable t which has return type of interface type e it gives the object type which is cont in the string . But when I print variable anno it just gives the return type which is the interface type Annotation .

What is the object type for variable anno ? Is there a way to find it ? Please help .





samedi 24 juin 2017

calling the static method in main class using reflection

this program recover the 2 group of the numbers from user that it compare then if the first one is bigger pointA receive one grade if not pointB receive one grade and it continues until last number.my problem is that i can't print the final result which the grade for pointA,pointB because of static method that i have in program.how can i print it there by using reflection or any other method?

public class Solution {
    static int[] solve(int a0, int a1, int a2, int b0, int b1, int b2){
      int pointA=0;
   int pointB=0;
        int FristArray[]={a0,a1,a2};
        int scoundArray[]={b0,b1,b2};
        for(int x=0;x<=FristArray.length;x++) 
        for(int y=0;x<=scoundArray.length;y++) 
            if (x>y){ 
                pointA+=1;
            }
        else if(x<y){  
            pointB+=1;
        }
       int points[]={pointA,pointB};
       return  points; 
    }

  public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int a0 = in.nextInt();
        int a1 = in.nextInt();
        int a2 = in.nextInt();
        int b0 = in.nextInt();
        int b1 = in.nextInt();
        int b2 = in.nextInt();
        int[] result = solve(a0, a1, a2, b0, b1, b2);
        for (int i = 0; i < result.length; i++) {
              System.out.print(result[i]+"i want to print it here");
        }
        System.out.println("");
        

    }




C# Delegate vs Reflection

I'm trying to optimize a method and can't get to the solution..

I have the following class:

public class X : MyInterface<Model>
{
    public void Execute(Model m) { }
}

I am trying to invoke Execute(...) I know the Type of X and I know the Type of Model.

This works:

(here logic to find the correct method).Method.Invoke(InstanceX, new object[] { m });

This does not but should work faster:

(here logic to find the correct method).Method.CreateDelegate(Expression.GetDelegateType(typeof(m)), instanceX);

Error: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

Again; trying to optimize, so any other solution that works faster than the reflection Invoke would be cool.





How to convert a Field class instance to Generic Instance

    import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;

public class calculation {
    static double pm10,pm2dot5,no2,o3,co,so2,nh3,pb;
    static HashMap<String, Double> concentration;
    static HashMap<String, Double> subIndex;
    static Scanner sc ;
    public static HashMap<Integer, Integer> _pm10,_pm2dot5,_no2,_o3,_so2,_nh3;
    public static HashMap<Integer, Double> _co,_pb;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
                indexCalculation();
    }
    static void indexCalculation () throws NoSuchFieldException, SecurityException
    {
        Iterator<String> gases = concentration.keySet().iterator();
        while(gases.hasNext())
        {
            String gas = gases.next();
            double value = concentration.get(gas);
            String str = "_"+gas;//this will create string instance like _so2,_nh3 etc..
            Class obj = calculation.class;
            Field field = obj.getField(str);
            Iterator<Integer> breakpoint = field.keySet().iterator();//unable to do..
        }
    }
}

  • How to convert field instance to HashMap instance ,so thay i can call keySet() method on it.
  • Or their any other to call an instance at run time.**




vendredi 23 juin 2017

Sorting by Reflection using GetProperty

I have a generic class with a method that needs to sort a generic entity.

However, an error occurs saying that it does not recognize the Reflection GetProperty method, since lambda can not translate.

How can I do this sort ordering logic?

public IEnumerable<TEntity> GetAll()
{
    var obj = _repository.GetAll()
        .OrderByDescending(x => x.GetType().GetProperty(typeof(TEntity).Name + "Id"));

    return obj.Pagination();
}

Here is the error image:

enter image description here





golang check length of a slice if it is a slice map[string]interface{}

I want to see if the type of v is a slice. If so, I wish to check the length of it.

var a = make(map[string]interface{})

a["a"] = 1
a["b"] = []string{"abc", "def"}
a["c"] = []int{1,2,3}

for k, v := range a {
    if reflect.TypeOf(v).Kind() == reflect.Slice {
        t.Log("Length of map", k, len(v)) // invalid argument v (type interface {}) for len
    }
}

How do I check the length of my slice, now that I know it is a slice?

Expected output:

Length of map b 2
Length of map c 3





Find subclasses of base class from external assembly

I am trying to create a list of sub classes for each class represented in my exported Types list. To be honest I am not sure how to do this, so my coding is mostly try and test.

Here is my list of classes.

public static Assembly asm = Assembly.LoadFrom(val);
List<Type> classes = asm.GetExportedTypes().Where(t => t.IsClass).ToList();

Here is my Foreach iteration where I try to attempt to find a list of Children of current class.

foreach (Type type in classes)
{
  List<Type> subclasses = asm.GetExportedTypes().Where(p => p.IsSubclassOf(type)).ToList();
}

I don't know if this is adding to my confusion but my assembly with all the information is excluded from my project, the main idea for my project is to find all inheritance trees for each class.

Basically my Question is how to iterate through each class and find all children that inherits from the current class.





jeudi 22 juin 2017

java generics and reflection,why different result

Test test = new Test() {}; there's nothing in {},why the result is different.

public class Test<T> {
    private final TypeToken<T> typeToken = new TypeToken<T>(getClass()) {};
    private final Type type = typeToken.getType();

    public void foo() {
        System.out.println(this.type);
    }

    public static void main(String[] args) {
        Test<Integer> test = new Test<Integer>() {};
        Test<Integer> test2 = new Test<Integer>();
        test.foo();// class java.lang.Integer
        test2.foo();//T
    }
}





C# function that returns type according to a parameter

I would like to create a function that returns new object according to the parameter, for example:

Base Class:

class BaseClass
{
    public int x;
}

Class One:

class TestCalssOne: BaseClass
{        
    public TestClassOne()
    {
        this.x = 1;
    }   
}

Class Two:

class TestCalssTwo: BaseClass
{
    public TestClassOne()
    {
        this.x = 2;
    }   
}

Main:

static void Main(string[] args)
{
    BaseClass bc = GetConstructor("TestClassOne");
    Console.WriteLine(bc.x); //Prints 1
}

static BaseClass GetConstructor(string className)
{
    if(className.Equals("TestClassOne"))
    {
        return new TestClassOne();
    }
    else if(className.Equals("TestClassTwo"))
    {
        return new TestClassTwo();
    }
    return null;
} 

The code I wrote works well, the problem is when I will have a lot of derived classes like TestClassThree, TestClassFour... TestClassThousand. How can I make a function that returns the correct constructor without if else or switch case and etc? I think that reflection would be a good option but I'm not really sure how to use it. Thanks!





what is class member named Void .ctor() in c# . this is appear when i use GetMethods [duplicate]

This question already has an answer here:

when i use GetType on Class, Void .ctor() is appear on DeclareMembers.

but this class has no member named Void .ctor().

what is Void .ctor()?





Howto get an assembly containing interface without Assembly.GetCallingAssembly()

I have a C# WinForms application and two assemblies involved - first contains an interface, second contains class which implements that inteface.

Application loads second assembly (via MS Enterprise Library Unity - i. e. via Reflection) and calls class methods.

I need to log that fact and before I was using the following code

var ApplicationInfo = Assembly.GetEntryAssembly().ToString();
var InterfaceInfo = Assembly.GetCallingAssembly().ToString();
var ImplementationInfo = Assembly.GetExecutingAssembly().ToString();

It was working correctly some time ago (it obtained application, first assembly and second assembly respectively).

But now for some reason GetCallingAssembly() and GetExecutingAssembly() both return second assembly (containing class inplementation).

Is there way to get an assembly containing interface without Assembly.GetCallingAssembly()?

Any idea why GetCallingAssembly() started to be equal GetExecutingAssembly()?





mercredi 21 juin 2017

Class List Across Packages Dynamically

I have the following problem:Can Reflection be applied across packages in java? For eg:I have two packages
Package First\src Class A
Class B
Class TestReflection
Package Second\src
Class D
Class E

Now in the class TestReflection,I have written the code to get all the class names given a Package dynamically using Reflection API's. It is working only if I give the package First\src but not with Packge Second\src.Can anybody please help me with this. I need to get the class names of all the packages irrespective of where my code is written?





Loading an unknown assembly via reflection in a PCL library

I am trying to load an object from an assembly via reflection.

My code that must do this is contained in a C# PCL library.

My progress so far:

I have successfully located the file path of the assembly. I think I know how to load the type I need from it, if I can get a valid assembly object of the dll.

Restrictions:

The only options I have on the Assembly class for loading is .load() I cannot move the dll to be in the same directory as the executable which is reflecting, even though that might work. I do not know the strong name of the assembly, as it is an unknown assembly in a folder.

A Side Note:

I am willing to use any library that does this.

The Question:

How do I load the assembly so I can reflect over it in a PCL library?





c# different delegate add in dictionary and run deleagate method from dictionary

With C#

I want to my delegate method into one dictionary, and put them all out and run.

for example

class class1{

Func<string,int> method1 = new Func<string,int>( x => 3);
Func<int,double> method2 = new Func<string,int>( x => 3.0);
Func<double,bool> method3 = new Func<string,int>( x => true);

Dictionary<string, dynamic> dic = new Dictionary<string, dynamic>();

dic.add("m1",method1)
dic.add("m2",method2)
dic.add("m3",method3)

// rund all method 

dynamic RunMethod(Dictionary<string, dynamic> dic , dynamic firstInput, int index = 0)
{
  if(index = dic.count) return 
  RunMethod(dic, dic.ElementAt[index].value(input) , index + 1)
}

void main ()
{
 RunMethod( dix , "firstString" )
}
}

(this code has error but expression of what i want to do )

What i want to do is like below.

  1. Create Method 1, 2 ,3
  2. Output type of Method 1 = Input type of Method2 , Output type of Method 2 = Input type of Method3 Finally get output of Method3

  3. There is Run Method that take Input that has type of method1 and method dictionary (or list or something)

  4. I want to additional method that check what type of method 1? and output type of method 3





EF6 Retrieving foreign key names from navigation property

I am trying to extract the structure of the entities in EF using reflection and then recreate it in memory (using DataSet) on a remote station.
I've managed to retrieve most of the information i need but i stumbled upon the relation between two entities using the navigation properties.
What I want to retrieve is the association between the entities and, from that association, the foreign key that constructs that association.
Given the structure from a Database First edmx:

enter image description here

I want to get the relation between the two tables that construct the navigation property "Versions"
I've noticed that this information is found in the edmx file under the association zone in the principal/dependent nodes enter image description here
but i cannot seem to obtain that same information in code in the RelationshipType property or in any other property enter image description here

Could you give me some help on how to proceed?
Thank you





is good to use reflection API on access of private method and variable?

i want to access a private method of class while writing Junit test cases.is it good to use reflection API.somewhere i found that reflection API is slow.so please give a suggestion





Accessing external Assembly Reflection

I am kind of new to Reflection and have gone through some basic examples, but I cannot figure out how to accomplish my goal.

I have a small console application which I want to call an assembly from. in this case the assembly is a Class Library Containing multiple classes and what I want to achieve is listing all of my classes with their children and parent classes.

       Assembly asm = Assembly.LoadFrom(@"C:\Sandbox\Functions\Bin\Debug\Functions.dll");

       Type T = asm.GetType();

So I have loaded the file but I am uncertain where to go now, how to use the metadata in order to access the necessary files and classes. Would appreciate some advice or references to other examples (Which I tried to search for).





Send a method implementation as parameter

Okay I am developing this library where I need the user to be able to implement his own implementation of a rendering method if "default" is not satisfactory, how would I do this?

I know it's possible to send functions in JavaScript and I think I need a similar construct in Java..

I have been considering lambdas and also the Method class of Java..

What would you guys say are my best alternative?





mardi 20 juin 2017

Getting the keys of an IDictionary property info without actual IDictionary object C#

In the scope I am working in, I have a property info that is an IDictionary. I need to get the keys of this IDictionary but do not have the actual IDictionary object, just the property info. How can I get all the keys of this IDictionary from the IDictionary Property Info Object.





How can I get a reference to a Kotlin KClass by name when not running on the JVM?

When targeting Javascript and native java.lang.Class.forName() is not available. How can I get a KClass in these environments?





How can I get a reference to a Kotlin object by name?

If I have a top level object declaration

package com.example

object MyObject {}

how can I convert the string com.example.MyObject into a reference to MyObject?





lundi 19 juin 2017

How can I use reflection to get a reference to a lambda that I can pass around?

I can use reflection to dynamically get a method and call it. How can I do the same with a lambda? IE something like

class Foo{
    public static String mapper(Object o){
        return "dummy val";
    }
}

class Bar {
    public static void main(String args[]){
        String[] arr = {"a", "b", "c"};
        Lambda reflectedMapper = ReflectionUtils.getLambda("Foo.mapper");//How do I actually write this line?
        List<String> mapped = arr.stream().map(reflectedMapper).collect(Collectors.toList();
    }
}





Divide a c# class into it's parts

if I have a Portable Class Library with a class

public class Class1
: EntityBaseClass
{
    public string Property1{get;set;}
    public string Property2{get;set;}
}

and a second class that contains an instance of class 1

public class Class2
: EntityBaseClass
{
    public string Property1{get;set;}

    public Class1 Property2{get;set;}
}

How can I devide class 2 so that I can get a dictionary in form of

Dictionary<Type, object>

where 'Type' is the type of Class1 and 'object' is the instance of class 1?

For persistence reasons I have to break a class into it's parts and have to save each instance separatly.

The plan is to implement a Save<T>(T entity) methode. This method picks out properties that derive from a special baseclass an save it into the datastore.

Because of the pcl library type there is no complete reflection subset of the .net Framework.

I tryed to do it with reflection and serialization without success but a lot of head aches. Attributes don't work too. Any hints how to start?





reflection - getMethods()/getDeclaredMethods() (Duplicate Methods!)

Consider the following simple Java code snippet:

package p;   

class Sup {
    public Sup f() {return null;}
}

class Sub extends Sup {
    @Override public Sub f() {return null;}
}

I used Java Reflection to list all the (declared) methods of the class Sub as follows.

for(Method m : Sub.class.getDeclaredMethods())
            System.out.println(m);

But I received an output like the following:

public p.Sub p.Sub.f()
public p.Sup p.Sub.f()

The first line is pretty reasonable, but the second one confuses me. Please explain why do I get the method public p.Sup p.Sub.f()? How does JVM distinguishes between the two methods at runtime during virtual method call resolution?

Thank you.





JavaScript: Difference between Reflect.get() and obj['foo']

Can't understand why I should use Reflect.get(obj, 'foo') instead of obj['foo'], or why the first one is useful as we can do the same thing using the good and old object bracket notation. Can someone please elaborate?

var obj = {foo: 'bar'};
obj['foo'];
Reflect.get(obj, 'foo');





Why does == and equals produce different results?

Executing the following code:

inline fun <reified> R> foorbar() {
    println(R::class == Double::class)
    println(R:class.equals(Double::class))
}

fun main(args: Array<String>) {
    foobar<Double>()
}

Produces the following output:

false
true

Why is there a difference between == and equals in this case? IntelliJ itself is suggesting that I replace the equals call with ==. Also, I could have sworn this code using == was working in the past.

Using kotlin version 1.1.0-rc91





Detect case class in scala macro

Within a method being called as a scala (2.11) macro, is there a way to programmatically determine whether a Type is a case class or not?

The API for the method I'm working through boils down to this:

def typeIsCaseClass(c: Context)(targetType: c.universe.Type): Boolean = {
  // targetType "is case class?"
}

I'm open to altering the API if need be.





Accessing variables thru reflection

I have a Windows Forms solution written in VB.NET. Using reflection from the Module MOD1 I want get/set public variable of Module MOD2. A strong constraint is to use just strings, as a command line interpreter would do. Here following there is the code I used to recreate the failing environment.

While accessing simple variable (useDialog) this code behaves as expected, but some problems rise while accessing complex variable (fWin or MainForm). I've made some mistake, but I don't realize which one!

Please note: fWin is a Windows Forms class.

Public Class fWin
    Public BoolValue As Boolean = True
    Public FileRoot As String = ""

    Private Sub fWin_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        mod1.MainForm = Me
        FileRoot = "My file root"
        mod2.Change()
    End Sub
End Class

Module mod1
    Public useDialog As Boolean
    Public PathRoot As String = "My path root"
    Public MainForm As fWin
End Module

Imports System.Reflection
Module mod2
    Dim currAssembly As Assembly = Assembly.GetExecutingAssembly()

    Public Function MemberSearch(memPathName As String, ByRef oParents() As Object) As Boolean
        Dim mcName() As String = memPathName.Split(".")
        Dim imc_scan As Integer
        Dim m_scan, currModule As [Module]
        Dim t_scan, currType As Type
        Dim f_scan, currField As FieldInfo
        Dim LoP As List(Of Object)

        currModule = Nothing
        currType = Nothing
        currField = Nothing
        LoP = New list(Of Object)
        Array.Resize(oParents, 0)

        imc_scan = 0
        For Each m_scan In currAssembly.GetModules()
            If (System.IO.Path.GetFileNameWithoutExtension(m_scan.Name) = mcName(imc_scan)) Then
                LoP.Add(m_scan)
                currModule = m_scan
                Exit For
            End If
        Next
        If (currModule Is Nothing) Then
            oParents = LoP.ToArray()
            Return False
        End If
        If (imc_scan >= (mcName.Length - 1)) Then
            oParents = LoP.ToArray()
            Return True
        Else
            imc_scan += 1
            For Each t_scan In currModule.GetTypes()
                If (t_scan.Name = mcName(imc_scan)) Then
                    LoP.Add(t_scan)
                    currType = t_scan
                    Exit For
                End If
            Next
            If (currType Is Nothing) Then
                oParents = LoP.ToArray()
                Return False
            Else
                If (imc_scan >= (mcName.Length - 1)) Then
                    oParents = LoP.ToArray()
                    Return True
                End If

                Dim bf As BindingFlags = BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.Public Or BindingFlags.NonPublic Or BindingFlags.IgnoreCase

                While (currType IsNot Nothing) AndAlso currType.IsValueType = False And (imc_scan < (mcName.Length - 1))
                    imc_scan += 1
                    currField = Nothing
                    For Each f_scan In currType.GetFields(bf)
                        If (String.Compare(f_scan.Name, mcName(imc_scan), True) = 0) Then
                            LoP.Add(f_scan)
                            currField = f_scan
                            Exit For
                        End If
                    Next
                    If currField Is Nothing Then
                        oParents = LoP.ToArray()
                        Return False
                    Else
                        Try
                            Dim Container As Object = LoP.Last
                            If (imc_scan >= (mcName.Length - 1)) Then
                                Container = LoP(LoP.Count - 2)
                            End If
                            currType = Container
                        Catch ex As Exception
                            currType = Nothing
                        End Try
                    End If
                End While
            End If
        End If

        oParents = LoP.ToArray()
        Return (imc_scan <= (mcName.Length - 1))
    End Function

    Public Sub Change()
        Dim ao() As Object

        Debug.WriteLine("")
        Debug.WriteLine("---------------------------------------------------")
        Debug.WriteLine("")
        If MemberSearch("sov_reflXn", ao) Then Debug.WriteLine(ao(0).Name)
        If MemberSearch("sov_reflXn.mod1", ao) Then Debug.WriteLine(ao(1).Name)
        If MemberSearch("sov_reflXn.mod1.useDialog", ao) Then Debug.WriteLine(ao(2).Name & " = " & ao(2).GetValue(ao(1)))
        If MemberSearch("sov_reflXn.mod1.PathRoot", ao) Then Debug.WriteLine(ao(2).Name & " = " & ao(2).GetValue(ao(1)))
        If MemberSearch("sov_reflXn.fWin.BoolValue", ao) Then Debug.WriteLine(ao(2).Name & " = " & ao(2).GetValue(ao(1)))
        If MemberSearch("sov_reflXn.fWin.FileRoot", ao) Then Debug.WriteLine(ao(2).Name & " = " & ao(2).GetValue(ao(1)))
        If MemberSearch("sov_reflXn.mod1.MainForm.FileRoot", ao) Then Debug.WriteLine(ao(3).Name & " = " & ao(3).GetValue(ao(2)))
    End Sub
End Module

The error "Additional information: Field 'BoolValue' defined on type 'sov_reflXn.fWin' is not a field on the target object which is of type 'System.RuntimeType'." occurs on the line starting with the following text: if MemberSearch( "sov_reflXn.fWin.BoolValue", ... The main problem is how to 'solve' fWin. I beg Your pardon for the delay of my previous post, and I thank You all in advance.





how to extract method from iqueryable and apply to new context

I have a subclassed ListBox with the following property:

Property Query As Func(Of IEnumerable)

this i use all over like this

MyListBox.Query=Function() MyDBContext.Products

or

MyListBox.Query=Function() MyDBContext.Clients.Where(function(x) x.Age>25)

etc

I now see that the way I use the Query property all over, never disposes of the MyDBContext, since I'm not using Using

so the question is:

Is there a way in my ListBox to grab only the function part of the func (i.e. .Clients.Where(function(x) x.Age>25) and apply it to a different dbcontext that i will use and dispose of internally in MyListBox?

Thank you very much





If there a way to get project root package from some class?

Imagine that I have such project structure:

/myProject
. /folder1
. . /subfolder2
. /folder2

Is there a way to receive a root package from class, which can be stored in any of these folders, during runtime? I need this in project, which I consider to be a library. These are the rows, where I need to get package name in runtime.

Reflections reflections = new Reflections(clazz.getRootPackageName());  // "com.myCompany" as a parameter, for example
Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);





how find out delegate return void ?

I want to know current delegate signature.

Especially I want to classify "Action" and "Func" deleagte.

like, if current delegate is action, run action and return current value,

and if func, run func and return result of func.





dimanche 18 juin 2017

How to change information of objects in a List with reflection?

I would like to read and manipulate the information from a List field. More specific, I would like to access the getter and setter of the nested List objects listedInnerClasses and hashMappedInnerClasses. I have hardly influence of the objects given into my observeAndReflect method. I don't know which Class will be passed into in the future.

public class ReflectMe {

private int id;
private long speed = 10;
private SimpleInnerClass simpleInnerClass;
private List<ListedInnerClass> listedInnerClasses;
private HashMap<Long, HashMappedInnerClass> hashMappedInnerClass;
// ... getter and setter
}

public class ListedInnerClass {

private long id;
private String foo = "bar";
// ... getter and setter
}

I filled in some stuff to test:

private void start() {

    // reflectionTest
    ReflectMe me = new ReflectMe();
    List<ListedInnerClass> listedInnerClasses = new ArrayList<ListedInnerClass>();
    ListedInnerClass aClass1 = new ListedInnerClass();
    ListedInnerClass aClass2 = new ListedInnerClass();
    aClass2.setFoo("bla");
    listedInnerClasses.add(aClass1);
    listedInnerClasses.add(aClass2);
    me.setListedInnerClasses(listedInnerClasses);
    try {
        observeAndReflect(me);
    } catch(IllegalAccessException e) {
        logger.error(e);
    }
}

And then I tried to get access. I started with the List:

private void observeAndReflect(Object o) throws IllegalAccessException {

    for (Field field : o.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        Class<?> fieldType = field.getType();

        logger.info("# Type: " + fieldType.getName() + " getName: " + field.getName() + " getValue " + field.get(o));

        if (fieldType == List.class) {
            // here I would like to change information of the lists objects
            logger.info("## My List: " + field.get(o));
            observeAndReflect(field.get(o));
        }
    }
}

My logoutput gives me some information:

INFO [main] (Runner.java:136) - # Type: int getName: id getValue 0
INFO [main] (Runner.java:136) - # Type: long getName: speed getValue 10
INFO [main] (Runner.java:136) - # Type: application.SimpleInnerClass getName: simpleInnerClass getValue null
INFO [main] (Runner.java:136) - # Type: java.util.List getName: listedInnerClasses getValue [application.ListedInnerClass@7bc1a03d, application.ListedInnerClass@70b0b186]
INFO [main] (Runner.java:139) - ## My List: [application.ListedInnerClass@7bc1a03d, application.ListedInnerClass@70b0b186]
INFO [main] (Runner.java:136) - # Type: long getName: serialVersionUID getValue 8683452581122892189
...

But I fail to get access to the information in my List.

As far as I understand, the information of the type parameter from the List gets lost due to type erasure. So the compiler does know there is a List, but forgets that there are objects of the Type ListedInnerClass in. I tried to reconvert that object but always ended up with the same problem: no access to getters and setters.

Is there still a way to get access to the information?

Thanks in advance!





Cast of generic property through reflection

I'm trying to retrieving a DbContext DbSet property by its name but I don't know how to handle the generic parameter.

DataSource.Load(IQuerable source) method comes from an external dll and I cannot modify it.

Knowing the property name of my DbSet prop (from an entity framework dbcontext class) I want to use that property value as parameter for DataSource.Load

 public class DataManager
 {

    private MyDbContext _dbContext;

    public DataManager(MyDbContext dbContext)
    {
        _dbContext = dbContext;
    }


    public object Load(string propName)
    {
        var source = _dbContext.GetType().GetProperty(entityName).GetValue(_dbContext, null);

        return DataSourceLoader.Load(source);         
    }

    //DataSourceLoader.Load signature:
    //DataSourceLoader.Load<T>(System.Linq.IQueryable<T>)





Is there a Typescript equivalant to Java/.NET Reflection? OR - How can I get a list classes extending a given abstract class?

Call me Noah.

// AnimalsBase: a package installed via 'npm install animals-base'
export default abstract class Animal {...}

There's this abstract base class, Animal, defined in an npm package, which gets extended by other packages:

// earth - I know about it because of 'npm install animals-earth'
import Animal from 'creatures-base'

export class Human extends Animal {...}
export class Cat extends Animal {...}
export class Dog extends Animal {...}
...

As you may know, I need to gather up collections that include every type of animal at runtime. Thing is, I'm never sure what planet I'll be working on any given day:

// tatooine - installed via 'npm install animals-tatooine'
import Animal from 'creatures-base'

export class WampRat extends Animal {...}
export class Bantha extends Animal {...}
export class SandPerson extends Animal {...}
...

I might even be expected to work several different planets on a given shift (deployment)...

Question One:

Can this function be written?

function animalCollection() : [Animal] {
    return [ /* An array containing one of each type of animal */ ]
}

Question Two:

If the above is possible, can I go further and discern the home planets of each animal?

function animalCollection(planet) : [Animal] {
    return [ /* An array containing one of each type of animal native to 'planet' */ ]
}





JAVA - Load Jar File and get File in src

I want to make a Programm which loads Jar Files from a Directory in my Programm. Want I'd like to do: The Loader should load the Jar an should searches for a Yml File in the src Folder of the Jar. When the Yml File was found, the loader should get the content of the File. In the File is the Location of the MainClass of the Addon. With this Location it can create an instance of the MainClass and give it back to my Programm. This is what I want. I searched a lot but nothing helped yet. I hope you can help me.





Find all types truly assignable to variable of a type

I am trying to find all types that are assignable to a variable of closed type, say ISteering<Foo> and have paremeterless constructor. Finding all types that directly implement(e.g. class A : ISteering<Foo>) it is trivial:

var type = typeof(ISteering<TreeMultiNode>);
var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(t => type.IsAssignableFrom(t))
            .Where(t => t.GetConstructor(Type.EmptyTypes) != null);

however I am strugging to find other types that also can be assigned, e.g.

//class DefaultSteering<T> : ISteering<T> where T : FooBase, ...
ISteering<Foo> st = new DefaultSteering<Foo>(); //fine for compiler

my research shows that IsAssignableFrom does not cover most of more complicated cases, typical solution to the problem is using GetGenericTypeDefinition:

type.IsAssignableFrom(t) || t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == type)

however it does not work in my case, no matter what I tried the type DefaultSteering<Foo> is never returned. (probably because my type is closed opposed to open type in similar questions).





How to get the Type of GenericDeclaration from ParameterizedType using Java Reflection?

I want to analysis the declared field variable in class MyComponent, and I want to get the GenericDeclartion's type of the field class, not the type it's declared in MyComponent. The demo is below.

public class SomeConfig<OP extends Operation> {
    private OP operation;

    public SomeConfig(OP op) {
        this.operation = op;
    }
}

public class MyComponent {
    private SomeConfig<?> config;

    public MyComponent(SomeConfig<?> config) {
        this.config = config;
    }
}

public class MyAnalysis {
    public static void main(String[] args) {
        Class clazz = MyComponent.class;
        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            Type type = f.getGenericType();
            if(type instanceof ParameterizedType) {
                 ParameterizedType pType = (ParameterizedType)type;
                 System.out.println(pType.getActualTypeArguments()[0]); // which prints "?" for sure
            }
        }
    }
}


The Problem: The printed result is "?" for sure. But all I want is to get the type of Operation to be printed instead of "?". Is it achievable?





Overriding method operations at runtime

I'm working on a game that has mods, and want to achieve the same effect that is achieved in Quake. When a mod folder contains a file with the same name as one in the stock code, the file is overwritten.
However I want to achieve something slightly different/better. I want to be able to do the previous action, but if the specific method is not implemented in the overwriting file, then use the default one that is provided in stock code.

I'm thinking of creating abstract classes that have all the abstract methods that people will need, and then storing the implementations in separate files. I don't however, know how to get this file to then "attach" itself to the abstract implementation like C/C++ does with headers and sources. Furthermore, how do I do this but also include the methods from my implementation, if they weren't specified in the secondary implantation.

So my question is, is there a way to overwrite the implementation of a class and its methods at runtime, given the location of the file containing the overriding classes/methods? And even better, (with a cherry on top), could I somehow seamlessly swap back and forth between implementations in the same runtime phase? (Probably asking for too much here)





samedi 17 juin 2017

Register class so it can be loaded safely via reflection

How can I "register" a class in a global scope, so that I can later on safely refer to this class and instantiate it via reflection?

Example scenario:

  • Assume a user sends a workflow_name via REST to a python server
  • The python server makes sure the requested workflow_name is the name of a concrete workflow class name which can be loaded via reflection

In pseudo code:

ConcreteWorkflow.py:

class ConcreteWorkflow1
    def doSomething(self):
        ...

# Somehow register the class in a global scope...???
regsiterWorkflow(ConcreteWorkflow1)

WorkflowRouter.py:

class WorkflowRouter
    def getConcreteWorkflow(self, workflowNameFromAPI):
        # somehow check if workflowNameFromAPI is one of the registered
        # concrete workflows. If so, load the class via reflection.
        ....
        concreteWorkflow.doSomething()

I hope the pseudo code makes it clear what I'm trying to achieve.





Kotlin Reflection operator get implementation

I'm learning Kotlin, current using Fedora 25 OpenJDK 8 and Kotlin 1.1.

I copied the example from the Kotlin website: http://ift.tt/1Tw1I9J and changed the get operator.

class Example {
var p: String by Delegate()
}

class Delegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        // My implementation
        return property.getter.call(thisRef) as String
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("$value has been assigned to '${property.name} in $thisRef.'")
    }
}

Reading the Reflection documentation the getter expects the object instance and no other parameter, but I only achieved the following error. (Error is abbreviate because it's too big, it's in recursion.)

.
.
.
at info.malk.Example.getP(Delegation.kt)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at kotlin.reflect.jvm.internal.FunctionCaller$Method.callMethod(FunctionCaller.kt:98)
at kotlin.reflect.jvm.internal.FunctionCaller$InstanceMethod.call(FunctionCaller.kt:115)
at kotlin.reflect.jvm.internal.KCallableImpl.call(KCallableImpl.kt:107)
at info.malk.Delegate.getValue(Delegation.kt:32)
at info.malk.Example.getP(Delegation.kt)
.
.
.
Caused by: java.lang.reflect.InvocationTargetException
    ... 1024 more
Caused by: java.lang.StackOverflowError
    ... 1024 more

Process finished with exit code 1

Help.





Java 'implements runnable' thread to execute reflection class

I am attempting to create an 'implements runnable' thread for a class of unknown name containing one parameterless constructor.

Current code:

Class<?> classEx = Class.forName("ArbitraryClassName.java").getClass();
Constructor<?> constructorEx = classEx.getConstructor();
Object objectEx = constructorEx.newInstance();

Thread threadEx = new Thread(objectEx);
threadEx.start();

However, I receive the error:

Cannot resolve constructor 'Thread(java.lang.reflect.Constructor<capture<?>>)'

How can a reflection be passed during thread instantiation?





Field.set throws IllegalArgumentException

I'm trying to do one-way data binding in java for swing objects, just as an exercise. Currently for swing objects that extend JTextComponent, I add a document listener that also updates the backing data storage.

public class Binder {

Map<JComponent, Map.Entry<WeakReference, Field>> map = new WeakHashMap<>();
AutoDocumentListener adl;

public Binder() {
    adl = new AutoDocumentListener();
}

public void bind(Object instance, String varName, JComponent element, String property) {
    Field field;
    try {
        field = instance.getClass().getDeclaredField(varName);
        field.setAccessible(true);
        map.put(element,
                new AbstractMap.SimpleEntry<WeakReference, Field>(new WeakReference(instance), field));

        if (element instanceof JTextComponent) {
            element = (JTextComponent) element;
            Document eldoc = ((JTextComponent) element).getDocument();
            eldoc.putProperty("origin", element);

            eldoc.addDocumentListener(adl);
        } else {  }
    } catch (NoSuchFieldException | SecurityException ex) {
        Logger.getLogger(Binder.class.getName()).log(Level.SEVERE, null, ex);
    }
 }

 class AutoDocumentListener implements DocumentListener {

    @Override
    public void insertUpdate(DocumentEvent evt) {
        JTextComponent jc = (JTextComponent) evt.getDocument().getProperty("origin");
        Map.Entry<WeakReference, Field> dataToUpdate = map.get(jc);
        if (dataToUpdate != null) {
            try {
                Object data = jc.getText();
                dataToUpdate.getValue().set(dataToUpdate.getKey(), data);
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                Logger.getLogger(Binder.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    @Override
    public void removeUpdate(DocumentEvent evt) {
    }
    @Override
    public void changedUpdate(DocumentEvent e) {
    }
  }
}

The problem is, at the following line I get a IllegalArgumentException:

dataToUpdate.getValue().set(dataToUpdate.getKey(), data);

java.lang.IllegalArgumentException: Can not set java.lang.String field org.jbind.test.TestClass.data to java.lang.ref.WeakReference

As far as I can see in the docs, the call to Field.set is correct. So, I don't understand what's going wrong.

I call the function with the following code:

public class TestClass {
public String data = "Text1";

public void init() {
    Binder binder = new Binder();

    JTextField jtf = new JTextField(data);
    binder.bind(this, "data", jtf, "");
    jtf.setText("Text2");
    System.out.println(data);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new TestClass().init();
        }
    });

  }
}





How to get declare properties name and its value

Please help me:

enter image description here

var myClass = new MyClass
 {
     FirstName = "John",
     LastName = "Nguyen"
 };

How can I get just 2 or more properties declared in myClass scope ?





vendredi 16 juin 2017

Replace (and backup) Method dynamically in C#

I need to change a specific property dynamically and have been using this snipplet:

var _oldMethod = typeof(TypeName).GetProperty("OldProperty", BindingFlags.Public | BindingFlags.Static).GetMethod;
var _newMethod = typeof(OwnTypeName).GetProperty("NewProperty", BindingFlags.Public | BindingFlags.Static).GetMethod;
ReplaceMethod(_oldMethod, _newMethod);

...

private static unsafe void ReplaceMethod(MethodInfo _oldMethod, MethodInfo _newMethod)
{
    var _oldMethodAddress = new IntPtr((int*)_oldMethod.MethodHandle.Value.ToPointer() + 2);
    var _destination = (uint*)_oldMethodAddress.ToPointer();
    *destination = (uint)_newMethod.MethodHandle.GetFunctionPointer().ToInt32();
}

Unfortunately this required some decompiling with recreating the original property. What I am looking for now is a a possibility to duplicate and kind of backup the original method and dynamically replace the old method with the new one or restore the original one.

Has anyone an idea how to implement this?





Get IReliableDictionary via reflection returns DistributedDictionary

I am trying to setup an IReliableDictionary with serialized state from external storage.

Thing is, the generic argument's types come as assembly qualified names - so to get the IReliableDictionary from StateManager, I need to create the generic method of GetOrAddAsync with type arguments that I provide, and invoke it on StateManager.

Next step is to use dynamic and call ContainsAsync and then SetAsync on this supposed-to-be-IReliableDictionary.

Turns out though, that I get a DistributedDictionary back, and it doesn't have those methods, so I get exception with 'object' does not contain a definition for 'ContainsKeyAsync'.

I fail to find a way to get an IReliableDictionary back, as I would normally do when not calling the method via reflection. What can I do here?





jeudi 15 juin 2017

create an instance from type with multiple constructor in scala

I have a class I created with 2 constructors.

I want to create an instance of this class using only default constructor.

class A (arg1:Int,Arg2:String){
   def this(arg1:Int){
      this(arg1,"hello")
   }
}

here is what I tries to do:

val tpe = ru.typeOf[A]
val mirror = ru.runtimeMirror(getClass.getClassLoader)
val clsSym = tpe.typeSymbol.asClass
val clsMirror = mirror.reflectClass(clsSym)
val ctorSym = tpe.decl(ru.termNames.CONSTRUCTOR).asMethod
val method = clsMirror.reflectConstructor(ctorSym)
val newInstance = method(args:_*)

I'm getting the following error:

constructor ExampleWithCamelCase encapsulates multiple overloaded
alternatives and cannot be treated as a method. Consider invoking 
<offending symbol>.asTerm.alternatives` and manually picking the required method

is there away to choose the default constructor?





Different data types in java

I am using reflection to extract the field type from Java objects at runtime. These fields are being categorized as:

  • Primitive Type
  • Fields having package name starting with Java.lang.*
  • Fields having package name starting with Java.util.*
  • Array types

For Custom Objects(User defined) in the field: These are again explored for their fields and their respective fields categorized.(Recursive call)

I wanted to know whether the above categorization will be enough for any object or some extra categories are required for more meaningful categorization.





How to properly query for a Constructor with an argument that is generic

I need to acquire the Constructor of a class at runtime using reflection instead of direct access. For simple types, this is trivial:

public class MyType {
    public MyType(String a, Integer b, Long c) {}
}

Constructor constructor = MyType.class.getConstructor(String.class, Integer.class, Long.class);

But if the class uses generics as part of its arguments, it's not clear what I should put:

public class MyType {
    public MyType(Set<String> a, Integer b, List<Long> c) {}
}

Constructor constructor = MyType.class.getConstructor(Set<String>.class /*Doesn't compile*/, Integer.class, List<Long>.class /*doesn't compile*/);

I can write something like MyType.class.getConstructor(Set.class, Integer.class, List.class); but it's not clear that that will achieve the behavior I want. What's the correct way to write this kind of code?





I'm trying to make a dynamically reflecting sphere with an orbiting box but the reflection "drags"

As I said in the title When my sphere reflects it drags the frame from before so instead of the live reflection of the cube I end up getting a full circle around the sphere.

here is my setup for the shapes.

var cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
var sphereGeometry = new THREE.SphereGeometry(3, 64, 64);
var smallSphereGeometry = new THREE.SphereGeometry(1, 64, 64);

var cubeCamera = new THREE.CubeCamera(0.1, 5000, 512);
scene.add(cubeCamera);

var mirrorShpereMaterial = new THREE.MeshBasicMaterial({envMap:cubeCamera.renderTarget });
var material1 = new THREE.MeshBasicMaterial({ color: 0xffff00, wireframe: false});

var cube = new THREE.Mesh(cubeGeometry, material1);
var sphere = new THREE.Mesh(sphereGeometry, mirrorShpereMaterial);
var smallSphere = new THREE.Mesh(smallSphereGeometry, material);

cube.position.x = 5;

then I add all the shapes to the scene and I attach the cube to the small sphere and rotate the small sphere to get the orbit effect.

next the render function

function render(){

            var delta = clock.getDelta();
            renderer.clear();



            sphere.visible = false;
            cubeCamera.updateCubeMap( renderer, scene );
            sphere.visible



            composer.render(delta); 
            requestAnimationFrame( render );
            smallSphere.rotation.y += 0.05;

            cube.rotation.z += 0.05;
            cube.rotation.x += 0.05;



        }
        var clock = new THREE.Clock()
        controls.update();
        render();

from what I understand the part here that should make the reflection dynamic the when i set the sphere to invisible the camera should then take a snapshot and update the material with the new position of the cube, but when I run it it doesn't update the new position it adds the new position while keeping all previous positions still on the sphere. So I'm wondering if I'm missing something here or how to do this differently.





C# reflection, get overloaded method

I've already checked a few other posts regarding reflection and overloaded methods but could find any help. One post I found was this one, but that didn't help a lot.

I have the following to methods:

1 | public void Delete<T>(T obj) where T : class { ... }
2 | public void Delete<T>(ICollection<T> obj) where T : class { ... }

I'm trying to get method N°1.

I tried the classic GetMethod("Delete") approach, but since there are two methods with this name a Ambiguous-Exception was thrown. I tried specifying the method schema with an additional parameter like GetMethod("Delete", new [] { typeof(Object) }) which didn't find anything (null returned).

I figgured I might as well just loop through all methods and check for the parameters. I have the following method...

public static IEnumerable<MethodInfo> GetMethods(this Type t, String name, Type schemaExclude)
{
    IEnumerable<MethodInfo> rm = t.GetRuntimeMethods().Where(x => x.Name.Equals(name));
    return (from runtimeMethod in rm let pis = runtimeMethod.GetParameters() where !pis.Any(x => schemaExclude.IsAssignableFrom(x.ParameterType)) select runtimeMethod).ToList();
}

... which returns the methods which do not contain a parameter with type schemaExclude.

I called it like this GetMethods("Delete", typeof(ICollection)) which didn't work as expected.

Apparently ..ICollection'1[T] is not assignable to ICollection. Neither is it to IEnumerable, IEnumerable<> and ICollection<>. I, again, tried it with typeof(Object) which did work but did return both methods (like its supposed to).

What exactly am I missing?





Cunstructor invocation failed using ReflectionClass in php

Following code was working earlier but now it's throwing error constructor invocation of class xyz failed:

code:

  $args = func_get_args();

  $obj = new ReflectionClass( 'xyz' );

  $instance = $obj->newInstanceArgs( $args );

Constructor:

public function __construct( SPImexCtrl &$proxy )
 {
  $this->proxy = &$proxy;
 }

My PHP Version: 5.6





Differences in Macros and Reflection in Meta-Programming

I'm currently studying about Meta-Programming. I guess Ruby on Rails uses meta-programming heavily. Here is what I understand so far.

  • Macros: Happens in compile-time, uses code to generate code (i.e. Rails uses attr_reader to automatically set up getters)
  • Reflection: Happens in run-time (I read reflection uses it's own language as a meta-language, but not sure what this means)
  • Meta-Programming uses a program as a data type to generate code; Macros and Reflection are techniques of Meta-Programming in some sense.

I have total 3 questions.

  1. I am having hard time to understand what Reflection is.
  2. What's the difference between Macros and Reflection
  3. Whether I can see Macros and Reflection as a subset of Meta-Programming since the definition of Macros and Meta-Programming almost seems identical to me.

If you can explain this in using Ruby/Rails, that would help me a lot. Thanks!





Obtain java.lang.reflect.Executable of current or calling method?

How can one obtain objects of the following types from specific instances of their represented language feature in the code:

  • java.lang.reflect.Executable
  • java.lang.reflect.Parameter

Ideally the providing method would be a caller of the obtaining method or the obtaining method itself.

Note that I have found two kinds of answers on SO:

  • how to get a Parameter from a given Executable object (trivial!)
  • how to get the name (not signature!) of a method from the call stack

Neither helps to obtain the Parameter to a particular method whose name is not unique.

Consider in particular how this answer and this one to similar questions gloss over the selection of the desired method.

Now, there exists Class.getMethod(String, Class<?>... types) but it does not seem that one could generate the "types" parameter automatically from an existing method definition?





Is it possible to determine descendants solely through Java reflection API?

Using Java reflection only, can we determine child (surbordinate) classes in a class hierarchy?





C# Reflection get variable's method nameof

I have selected a static method and assigned it to variable like so:

var reflectionedMethod =
    typeof(MyType)
    .GetMethod(
        nameof(MyMethod),
        BindingFlags.NonPublic 
        | BindingFlags.Public 
        | BindingFlags.Static 
        | BindingFlags.FlattenHierarchy,
        null,
        new Type[] { typeof(TArgs) },
        null);
// IN THIS IF STATEMENT IS THE ACTUAL QUESTION'S PROBLEM 
if (reflectionedMethod == null)
{
    new NotImplementedException(string.Format("{0} not implemented!", nameof(MyMethod)));
}

Question:

What is the best way to get method from a variable (not just like nameof(MyMethod)) into

new NotImplementedException(string.Format("{0} not implemented!", [INSERT HERE SOLUTION PLEASE]));





Kotlin language get class at runtime

Let's say that we have the following:

val person = "Bill"

Could someone explain the difference between these two:

val kClass1 = person.javaClass.kotlin

vs

val kClass2 = person::class

When I should call the one instead of the other?





mercredi 14 juin 2017

Deep Clone of code first EF Entity

I am attempting a Generic Deep Clone Routine for code first Entity Framework entities.

I've cracked it for the standard System property types but am having trouble with Proxy Entities (defined with virtual) i.e.

[EntityLookup]
public virtual Person { get; set; }

[EntityLookup] is one of my own attributes that helps further define the Association.

If I remove the "virtual" keyword, my routine can update the destination entity property no problem (but I lose the additional EF functionality) With virtual I get the following error;

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

I believe it's all to do with EF's Proxy class but I'm not sure how to cast the original entity so I can set it on the destination. Below are the essentials of the Clone routine for this issue;

public static void CloneProperties<T>(T Original, T Destination)    
{
    PropertyInfo[] props = Original.GetType().GetProperties();
    foreach (var propertyInfo in props)
    {
        if (propertyInfo.PropertyType.Namespace == "System" || propertyInfo.PropertyType.IsEnum)....
        else
        {
                if (Destination.PropertyHasCustomAttribute (propertyInfo.Name, typeof(EntityLookupAttribute)))
                {
                    var pv = propertyInfo.GetValue(Original, null);
                    propertyInfo.SetValue(Destination, pv, null);
                }
         }
    }
}

It's the "propertyInfo.SetValue(Destination, pv, null);" that generates the error when the entity is declared virtual.

Any help on getting it to work will be gratefully accepted

Best Regards

Lance





Change Custom Attribute Value On Property Of Instantiated C# Class

I have the following class

public class IndexData
{
    [CustomAttribute(Constants.SomeStringName)]
    public string Title { get; set; }

    [CustomAttribute(Constants.AnotherStringName)]
    public string Description { get; set; }
}

I want to be able to change the values (The string value) of [CustomAttribute(string)] in an instantiated version of the class. A simplified version of what I am trying to acheive would be.

var indexData = new IndexData();

if(SomeCriteria){

  // Need to change the attribute value here
  // indexData.Title.CustomAttribute.Value = "SomethingElse"
}

// Continue with data mapping
indexData.Title = "Something"

I can't change the attribute as it's a custom attribute from another API (Azure Search). So I need a way of changing the values of the attributes after I have instantiated the class.

As there may be several different criteria. Hope that makes sense? And any help/guidance would be appreciated.





How can we maintain mutability of a class with reflection in Java?

I am aware about the concept of immutability of a class and how to make a class immutable, but there are certain ways that can break the immutability of that class like reflection, serialization etc. So I want to know the way to maintain the mutability of a class with reflection.





running dependency main function

I am having two java projects, animal project and animal-test project. In animal project I am having an annotation interface called Animal like as shown below

Animal.java

package com.animal;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Animal{
    String name();
} 

Along with this I am having an interface MakeSound.java which has a method called makesSound(). AnimalFinder.java. The source code for MakeSound.java and AnimalFinder.java is as given below

MakeSound.java

package com.animal;

public interface MakeSound {
    public void makesSound();
}

AnimalFinder.java

package com.animal;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;

import org.reflections.Reflections;

public class AnimalFinder {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        System.out.println("checking....");
        Reflections reflections = new Reflections();
        Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Animal.class);
        for (Class<?> class1 : annotated) {
            Animal animal= class1 .getAnnotation(Animal.class);
            if (animal.name().equals("cat")) {
                Object customAnnot = class1.newInstance();
                Method[] methodArr = class1.getDeclaredMethods();
                for (Method method : methodArr) {
                    String methodName = method.getName();
                    if (methodName.equals("makesSound")) {
                        method.invoke(customAnnot);
                    }
                }
            }
        }
    }
}

Now I have build and created animal jar file including the dependencies, then I have imported animal.jar in my Second Project animal-test. I create a class called AnimalTest.java like as shown below

package com.myanimaltest;

import com.animal.MakeSound;
import com.animal.Animal;

@Animal(key = "cat")
public class SampleAnimalTest implements MakeSound {
    public void makesSound() {
        System.out.println("Meowwww");
    }
}

I now build and create a jar file animal-test.jar and when I run the jar file like java -jar animal-test.jar I got the following exception

no main manifest attribute, in animal-test.jar

Can anyone please help me on this. My expectation that I am able to get "Meowwww" printed

The pom.xml for the two project is given below

pom.xml (animal)

<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>com.animal</groupId>
    <artifactId>animal</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>

    <name>animal</name>
    <url>http://ift.tt/19pvvEY;

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.7</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.10</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4.1</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>com.animal.AnimalFinder</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

pom.xml (animal-test)

<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>com.myanimaltest</groupId>
    <artifactId>myanimaltest</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>

    <name>myanimaltest</name>
    <url>http://ift.tt/19pvvEY;

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.7</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>animal-1.0</groupId>
            <artifactId>animal-1.0</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/libs/animal-1.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>animal-1.0-jar-with-dependencies</groupId>
            <artifactId>animal-1.0-jar-with-dependencies</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/libs/animal-1.0-jar-with-dependencies.jar</systemPath>
        </dependency>
    </dependencies>
</project>