dimanche 31 juillet 2016

I can not compare elemets by fields in two Lists

I have Entity User

class User{
private Long id;
private String Name;
private List<SomeClass> someClass;
}

And Entity SomeClass

class SomeClass{
    private Long id;
    private String Name;
    }

I have two object User

user1 and user2

user1.getSomeClass().size() == 5;
user2.getSomeClass().size() == 5;

I need to compare all the elements user1.someClass and user2.someClass

but I do not understand how to do it. how to match any element to which refers. I have bad English but I'll try to explain. I create the first user and create some someClasses for him. After that I try to edit this user. Editing is as follows: I create a new user and copies the old data, if the data is not changed, and if any new fields that have changed. I get the new user - user2. It may so happen that I will edit the item3 of someClass of user2. And After that I need compate this two lists and detect change in it.

if (fromField.getType().equals(List.class)) {
                    List listCurrent = (List) fromField.get(current);
                    List listOld = (List) toField.get(old);
                    for (Object o : listCurrent) {
                        for (Object oldItem : listOld) {
                            if (!oldItem.equals(o)) {
                                //I get each elemet of listCurrent and compare with each element of listOld. but how am I to understand that this object from the first list refers to the objects from the second id if the elements are different? equals method will compare each items in oldItem list 
                        }
                    }

I need to understand whether the new element was added or removed, or modified in user2.someClass





Why is MethodImplAttributes not marked with FlagsAttribute?

    /// <summary>
    /// Specifies flags for the attributes of a method implementation.
    /// </summary>
    [ComVisible(true)]
    [__DynamicallyInvokable]
    [Serializable]
    public enum MethodImplAttributes
    {
      [__DynamicallyInvokable] IL = 0,
      [__DynamicallyInvokable] Managed = 0,
      [__DynamicallyInvokable] Native = 1,
      [__DynamicallyInvokable] OPTIL = 2,
      [__DynamicallyInvokable] CodeTypeMask = 3,
      [__DynamicallyInvokable] Runtime = 3,
      [__DynamicallyInvokable] ManagedMask = 4,
      [__DynamicallyInvokable] Unmanaged = 4,
      [__DynamicallyInvokable] NoInlining = 8,
      [__DynamicallyInvokable] ForwardRef = 16,
      [__DynamicallyInvokable] Synchronized = 32,
      [__DynamicallyInvokable] NoOptimization = 64,
      [__DynamicallyInvokable] PreserveSig = 128,
      [ComVisible(false), __DynamicallyInvokable] AggressiveInlining = 256,
      [__DynamicallyInvokable] InternalCall = 4096,
      MaxMethodImplVal = 65535,
    }

Why is this enum not marked with the FlagsAttribute? It is used like bitfields in all examples you can find on MSDN and most of the guidelines for the attribute on MSDN match this definition.

MethodBuilder.SetImplementationFlags() even implies that it is used like an enum marked with [Flags] aside from the MSDN example code.





When trying to set a private static final field using reflections, I get an error saying I cannot set the object to another object

I am working on a plugin for a Minecraft server to change an item type to another item type (using reflections). I have most of it finished, but I have run into an issue setting a single field. code:

Field WHEAT = Items.class.getDeclaredField("WHEAT");
Method get = Items.class.getDeclaredMethod("get", String.class);
get.setAccessible(true);
WHEAT.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(WHEAT, WHEAT.getModifiers() & ~Modifier.FINAL);
WHEAT.set(null, (Item) get.invoke(null,"wheat"));

I have gotten this far via this thread:Change private static final field using Java reflection

but I cannot figure out where to go from here. Anyone have any suggestions?





Create Expression from string params[]

I have a function that want in input an expression of object.

ColumnsToUpdate<T>(params Expression<Func<T, object>>[] properties)    
Update(books, b => b.ColumnsToUpdate(b => b.Author, b => b.Name));

But I have a list of strings

string properties = "Author,Name";

And I want convert it in one compatible expression for use with the ColumnsToUpdate method.





samedi 30 juillet 2016

How to load an assembly and get all types in it with C# (without ReflectionTypeLoadException)

I'm trying to build a plugin architecture where dlls are included in a zip file, unzipped, stored, then loaded so that a specific type can be constructed and worked with. In theory, it sounds doable. But I'm having an issue with it. I keep getting a

ReflectionTypeLoadException.

Here's what I have that isn't working:

        var dlls = pluginFiles.Where(p => p.Value.FileInfo.Extension.ToLower() == ".dll").ToList();
        int num = 0;
        foreach(var dll in dlls){
            var assembly = Assembly.LoadFile (dll.Value.FileInfo.FullName);
            var pluginTypes = assembly.GetTypes().Where (p => p.IsSubclassOf (typeof (Plugin)));
            foreach(var pluginType in pluginTypes){
                var ctor = pluginType.GetConstructors ().FirstOrDefault ();
                if (ctor == null) continue;
                var plugin = (Plugin)ctor.Invoke (new object [] { });
                if (plugin == null) continue;
                num++;
                _mgr.RegisterNew (plugin);
            }                      
        }

As I'm stepping through this in debug, the exception happens on the line where I'm running assembly.GetTypes().

What am I doing wrong here? Should I be doing something with a new AppDomain?

Further info: The assembly I'm loading is a test assembly. It does have a reference to FakeItEasy. It has a single class, which is the class I'm looking for.

I've looked at this. It seems like it might be applicable, but I can't fully tell how (and I don't quite understand why that answer works for that question).





Java load class from Jar and handover complex data type

I would like to load a class from another JAR (imported as file during runtime) and handover an Object (this) to the Constructor of the class which should be loaded.

I tried doing that with the following code:

URLClassLoader cl2 = URLClassLoader.newInstance(new URL[] { new URL("jar:file:" + jarPath +"!/") });
Class c2 = cl2.loadClass("main.Class2BeLoaded");
Object loadedClass = c2.getConstructor(Object4Constructor.class).newInstance(this));

It seems so, that the Object which I handover to the constructor (this) can't be used from the code which runs in the JAR.

What is wrong? If I run this code in the same JAR everything works.





vendredi 29 juillet 2016

Which Class method generates the right input for Class.forName()?

I would like to write some code like this:

Object o = ...;
String oTypeName = o.getClass().getName();

//on the other side of the wire:

Class<?> oClass = Class.forName(oTypeName);
Object oAgain = oClass.newInstance();

However, it's not clear from the javadoc which method I should use to initialize oTypeName, i.e. which method will produce the expected input to Class.forName():

  • getCanonicalName(): "Returns the canonical name of the underlying class as defined by the Java Language Specification. Returns null if the underlying class does not have a canonical name (i.e., if it is a local or anonymous class or an array whose component type does not have a canonical name)."
  • getName(): "Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String. If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by The Java™ Language Specification."
  • getTypeName(): "Return an informative string for the name of this type."

It's fairly obvious that I don't want either of these:

I don't expect this to work for primitive types. It's okay if it won't work for arrays. The main thing I'm concerned about is inner classes and Foo.Bar vs. Foo$Bar.





Run Junit Test on a dynamically Loaded class

i have a problem at the moment doing a project at university. Basically i have to get the source code of a class , compile it and then execute a Junit test on it. I managed in many ways to compile dynamically my code, generating a .class file, so that's not the problem.

Since this procedure is done dynamically, how can i invoke methods and constructors of this class in the junit test case without using Java reflection?

Thanks in advance and sorry for my bad english!





C# Reflection, setting new instance of a null property

I've writing a small method whose sole purpose is to check if a property is null for a given class. If the property is null, then create a new instance of it. I'm getting stuck on part where I'm actually setting a value:

  public static void CheckIfPropertyIsNull<TEntity>(SomeBusinessEntity someBusinessEntity) where TEntity : new()
    {
        var properties = typeof(SomeBusinessEntity).GetProperties();

        foreach (PropertyInfo propertyInfo in properties)
        {
            Type currentType = propertyInfo.PropertyType;
            if (currentType == typeof(TEntity))
            {
                var propertyData = propertyInfo.GetValue(someBusinessEntity, null);
                if (propertyData == null)

                {
                    object instance = Activator.CreateInstance(typeof(TEntity));

                    // And then?
                    //propertyInfo.SetValue(null, instance);

                    return;
                }
            }
        }
    }

I try to use the SetValue() method but with no luck.





Does a C# property setter not get called when value set via Reflection?

I have a complex recursive reflection logic written where an entity property is being set via reflection. But i can see that the setter of that particular is not called.

Is this possible..? If yes, is there a way to make the setter for the property to run. (I am aware, that getter and setters are essentially functions in their inner implementation)





PlayFramework 2.5 - Ebean update using reflection


I'm developing a website with an inline editor using Play framework 2.5 and Ebean as ORM, and I have a news section where the admin can edit every single news (editing fields inline such as title, content and so on).
In order to do so, I set every html element which can be modified with an id equals to the news model field (e.g. the html element mapping the field title will have id="title"), then when I receive data from the client, I use reflection on the controller to map every content with the correct news field.

Here is the code (EditContent is an object which contains informations like the id and the htmlContent of every modified content):

News news = News.find.byId(newsId);

for(EditContent content : pageContents.contents) {
    Field field = news.getClass().getField(content.cssId);
    field.setAccessible(true);
    field.set(news, content.htmlContent);
}

news.update();

The problem is that the update seems to be executed, but actually values are not updated on db. Using debugger, I inspected the object news and I can see that the fields are modified properly, but then the update has no effects on db.
Also, I noticed that the same code using:

News news = new News()
...
//reflection to save modifed contents in the new object
...
news.save()

works as I expect, saving a new row in the database.

Any idea?

Thank you in advance for your help!





jeudi 28 juillet 2016

How to reflect a point around a line in hexagonal coordinates

I have a hexagonal coordinate system as shown here:

The hexagonal coordinate system I use.

(If you'd like a better understanding of the coordinate system, I learned it from here)

I would like to reflect points (hexagons) across given lines. In fact, the only lines I need to reflect across are those defined by the border of (0, 0) and the other hexagons around it.

For example, the border of (0, 0) and (1, 0) creates a line. (0, 1) and (1, -1) would both be points on this line. The hexagon bordering (0, 0) that helps define the line (in this case, (1, 0)), I'll call the "bordering hexagon".

My question is this: Is there an easier algorithm than the one I describe below that takes the coordinates of the bordering hexagon and another hexagon on the grid (called the objective hexagon), and returns the coordinates of the objective hexagon after a reflection over the line defined by (0, 0) and the bordering hexagon?

My current method is:

  1. Use the coordinates of the bordering hexagon as a vector perpendicular to the reflection line
  2. Take the coordinates of the two bordering hexagons surrounding our original bordering hexagon, and subtract them (x2-x1, y2-y1) to get a vector parallel to the reflection line
  3. Use a change of coordinates matrix to convert the coordinates of the objective hexagon into parallel and perpendicular components such that (perpendicular component)*(perpendicular vector)+(parallel component)*(parallel vector) = (objective hexagon coordinates)
  4. The result of the reflection is then (objective hexagon coordinates)+2*(perpendicular component)*(perpendicular vector)

Does anyone know of a better way? This seems fairly complicated for such a seemingly simple problem.





How can I get an object from a different assembly?

I have a Web API project whose assembly I've gotten with

Assembly ass = typeof(SomeClassInTheAssemblyIWant).Assembly;

Now I want to access the same object that is accessed by

System.Web.Routing.RouteTable.Routes

within the project for that assembly.

Hope that makes sense.





C# Portable class library and reflection with nested properties

I would like to know how to set property into a nested class with reflection on Xamarin portable class library.

I am working on a project with reflection on a Xamarin portable class library.

I have this code:

public class Customer
{
    public string Name { get; set; }
    public string FirstName { get; set; }
    public int Id { get; set; }        
}

public class Invoice
{
    public string Description { get; set; }
    public int Id { get; set; }

    public Customer Person { get; set; }
}

on the other hand I have this function:

    public void TestCode()
    {
        var myCustomer = new Customer()
        {
            FirstName = "qwerty",
            Name = "asdfgh",
            Id = 1
        };

        var myInvoice = new Invoice()
        {
            Description = "chocos",
            Id = 1,
            Person = myCustomer,
        };

        var properties = myInvoice.GetType().GetRuntimeProperties(); 

        foreach (var property in properties)
        {
            var value = property.GetValue(myInvoice);
            if (value != null)
            {
                if (property.PropertyType.IsGenericParameter)
                {
                    //Have Generic parameters
                }
                else
                {
                    //How I Know if my class == person???
                }
            }
        }
    }

When I have the string property and I use (for example) GetRuntimeProperties() this function returns about 8 properties so the question is:

How do I know if the property is my class?

Other example: How I get person.Name value from the Invoice?

Thank you





Charging runtime libraries

Is there any contraindication to load libraries (.jar) at runtime?

I found this code that does this:

    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class sysclass = URLClassLoader.class;

    try {
        Method method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class});
        method.setAccessible(true);
        method.invoke(sysloader, new Object[]{URL_LOAD});
    } catch (Throwable t) {
        t.printStackTrace();
        throw new IOException("Error, could not add URL to system classloader");
    }

     

This code works. But it is the best way?

I want to load at run time for new jars can be placed in a folder and thus carry new features to my system. As if they were additional modules.





Force a class to implement a specific constructor [duplicate]

This question already has an answer here:

Let's say I have the following class:

public class SomeClass<TSource>
{

     private Model _model;

     // ...

     public void SomeMethod()
     {
         // ...
         TSource instance = Activator.CreateInstance(typeof(TSource), _model);
         // ...
     }
}

And then I have this class:

public class OtherClass
{
     public OtherClass(Model model)
     {
         // ...
     }
}

If I do the following, everything's fine:

SomeClass<OtherClass> someClass = // ....
someClass.SomeMethod();

But what if OtherClass has a parameterless constructor, or any constructor different than the stated?

Everything will compile just fine, but when creating the instance a runtime exception will be raised.

Is there a way to enforce the use of a certain constructor on every class that will be used as a generic argument to SomeClass<> ? (Like a generic constraint)





Translate Java code into Eclipse and Javac AST injection statements

I am facing the following issue: I need to develop custom Lombok annotation handlers, and these handlers should inject quite complex methods into the objects. Since it's a research project, the content of the method is likely to change and I'm looking for a way to automate some manual tasks.

As well described in this post, the greatest pain in the process of creating custom handlers is two implement twice, once for Eclipse and once for Javac, the AST injection code that add the method statements.

So my question is the following: are there any tools/projects around that takes as input a Java file and the method name one wants to inject, and that outputs the Java code (for both Eclipse and Javac) that will insert this method into the handler ?





reflection while targeting several framworks

I have a library targeting .net core and net45 at some point on my code I need to use reflection like this:

var type = obj.GetType();
var properties = type.GetProperties().ToList();

if (type.IsPrimitive || type.IsEnum || properties.Count == 0)
    return new Dictionary<string, object> { { unnamed, obj } };

Now I am porting my library to also support .net core so I made a new .net core library project, this is my project.json

{
  "version": "1.0.0",
  "dependencies": {
    "Wen.Logging.Abstractions": "1.0.0"
  },
  "frameworks": {
    "net45": {
      "frameworkAssemblies": {
        "System.Reflection": "4.0.0.0"
      },
      "dependencies": {
        "Newtonsoft.Json": "6.0.4",
        "NLog": "4.3.5"
      }
    },
    "netstandard1.6": {
      "imports": "dnxcore50",
      "dependencies": {
        "NETStandard.Library": "1.6.0",
        "System.Reflection.TypeExtensions": "4.1.0",
        "Newtonsoft.Json": "8.0.2",
        "NLog": "4.4.0-*"
      }
    }
  }
}

added my classes and the compiler complains about the type.IsPrimitive and types.IsEnum properties so I thought to use compiler directives to do something like this:

var type = obj.GetType();
var properties = type.GetProperties().ToList();

#if net45    

if (type.IsPrimitive || type.IsEnum || properties.Count == 0)
    return new Dictionary<string, object> { { unnamed, obj } };

#elif netstandard16

//... some code

#endif

Once I do this the code inside the net45 is grayed out (I think because VS is seeing it as .net core) but then no matter what tag I set between the #elif and #endif is also grayed. I have also tried with #else and then I can do:

var typeInfo = type.GetTypeInfo();
if(typeInfo.IsPrimitive || typeInfo.IsEnum || properties.Count == 0)
    return new Dictionary<string, object> { { unnamed, obj } };

however my question remains:

What tags should I use on my code on the compiler directives #if to target several frameworks on the same project/library?





Copy a Nullable property to a non-Nullable version using Reflection

I am writing code to transform one object to another using reflection...

It's in progress but I think it would boil down to the following where we trust both properties have the same type:

    private void CopyPropertyValue(object source, string sourcePropertyName, object target, string targetPropertyName)
    {
        PropertyInfo sourceProperty = source.GetType().GetProperty(sourcePropertyName);
        PropertyInfo targetProperty = target.GetType().GetProperty(targetPropertyName);
        targetProperty.SetValue(target, sourceProperty.GetValue(source));
    }

However I have the additional issue that the source type might be Nullable and the target type not. e.g Nullable<int> => int. In this case I need to make sure it still works and some sensible behaviour is performed e.g. NOP or set the default value for that type.

What might this look like?





Unable to find private void generic function with GetMethod

I have a function with the following signature:

private void Foo<TPoco>(IContext context, List<TPoco> pocos, DateTime modifiedDateTime)
    where TPoco : MyAbstractClass

And I cannot find this function in GetMethods().

Based on this SO post ( GetMethod for generic method ), I have tried these binding flags:

GetType().GetMethods(BindingFlags.Public 
    | BindingFlags.NonPublic 
    | BindingFlags.Instance 
    | BindingFlags.Static 
    | BindingFlags.FlattenHierarchy
)

And this finds 14 other methods in the class, but not this one. It does find this method:

protected void Bar<TContext, TPoco>(List<TPoco> pocosToPersist, TContext context)
    where TContext : IContext, new()
    where TPoco : MyAbstractClass

So the only difference is the access level - but then I can see other private functions.

Even if I change the binding flags to something simpler (which, from what I understand, shouldn't make new items visible):

GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance )

I still don't see the function.





Finding instance of method

This question is for utility script for Unity3D, but the problem is just in C#;

I am providing the script with string (onClickCallbackPath) that looks something like "GameObjectName.ComponentTypeName.CallbackDelegateName".

Finding GameObject and Component is not a problem, but take a look at this code:

    string[] ss = onClickCallbackPath.Split ("." [0]);
    Transform onClickTarget = Tools.FindDeepChild (transform.root, ss [0]);
    MonoBehaviour[] allComponentsOnTarget = onClickTarget.GetComponents<MonoBehaviour> ();

    foreach (MonoBehaviour mb in allComponentsOnTarget) 
    {
        if (mb.GetType ().Name == ss [1]) 
        {
            MethodInfo[] methods = mb.GetType ().GetMethods (BindingFlags.Public);

            foreach (MethodInfo mi in methods) 
            {
                if (mi.Name == ss [2]) 
                {
                    // And here is how I imagine it to work, and look for something similar...
                    // but of course there is no GetInstance method in MethodInfo
                    Action a = (Action) mi.GetInstance(mb);
                    break;
                }
            }

            break;
        }
    } 

As you can see I need to find an object of Action type (I am making sure it is method with correct signature), from within the MonoBehaviour I found.

I tried to take a look at all MethodInfo properties to have something like that I am looking for, also tried to find solution in the net (also here on SO) but without success. I bet my problem with finding solution is just wrong naming the problem.

But I hope you understand what is my problem.

Any help appreciated.





Find class marked with annotation of a specific value

I'm using this Java Reflections API that I'm finding quite convenient so far:

http://ift.tt/Ofz26b

Find all classes marked with a specific annotation is dead easy, however, I can't figure out how to add a filter in the scanner to retrieve classes that have that annotation configured in a certain way.

For example, if I have three classes:

@Important(level="high")
public class HighlyImportant { }

@Important(level="medium")
public class ModeratelyImportant { }

@Important(level="low")
public class NotSoImportant { }

I can get all three classes by scanning for the @Important annotation, but how do I restrict that to only @Important(level=high) ?

Thanks





mercredi 27 juillet 2016

How do you declare a variable with the type being a generic class that you DONT have access to without reflection?

Example of what I want:

Seperate jar file:

class poop<T extends Someotherclass>{

}

Another Jar File(main one):

class pee{

    //i want the type of the variable to be poop<?>, but using reflection.
    poop<?> a = reflectionStuff;
}

I have searched, and the closest I got was this method

Field.getGenericType()

I supposed you could cast a variable to a another Class variable? Im not sure





Instantiate from .java file

I would like to instantiate a list of objects from a certain directory without previous knowledge of their existence. I do however know that the classes all inherit from the same parent.

Directory

Some.java 
SomeOther.java 
YetAnother.java

I have tried to use the URLClassLoader as such:

URLClassLoader.newInstance(new URL[]{file.toURI().toURL()})

But cannot create the class because I do not know its name in advance.

How can I create an array of objects from a list of .java files.





TypeScript - passing a class as an argument, and reflection

I am writing a generic unmarshaller. It converts graph DB data to generated TypeScript (1.8.7) model classes. The input is JSON. The output should be an instance of a model class.

What's the right way to pass a class as a parameter and reach it's static members?

I've tried to write a method. Not sure if I am heading in the right direction, feel free to suggest different approaches.

public fromJSON(input: Object, clazz: typeof FrameModel): FrameModel
{
    clazz.graphPropertyMapping;
    clazz.graphRelationMapping;

    let result = {};
    ...
    return result;
}
...
SomeModel some = <SomeModel> unmarshaller.fromJSON({...}, SomeModel);

But when I tried to execute this on Plunker, I got execution errors with unuseful stacktrace.

The model looks like this:

import {TestPlanetModel} from './TestPlanetModel';
import {TestShipModel} from './TestShipModel';

export class TestGeneratorModel extends FrameProxy
{
    private vertexId: number;

    private const discriminator: string = 'TestGenerator';

    private const graphPropertyMapping: { [key:string]:string; } = {
        bar: 'boo',
        name: 'name',
        rank: 'rank',
    };


    private const graphRelationMapping: { [key:string]:string; } = {
        colonizes: 'colonizedPlanet',
        commands: 'ship',
    };

    boo: string;
    name: string;
    rank: string;

    public colonizedPlanet: TestPlanetModel[]; // edge label 'colonizedPlanet'

    public ship: TestShipModel; // edge label 'ship'

}

I haven't found much material on reflection and class handling in TypeScript.
I know how I would do this in Java.
I know how I would do this in JavaScript.
I understand that I might achieve similar results with decorators, but having fields or static fields seemed a bit simpler, for generated models.





Length of array regardless of type [duplicate]

This question already has an answer here:

I'm doing some error handling on objects that could be any type, and I want to have special handling for arrays. What I can't figure out is how to get the length of the array regardless of whether it's an array of primitives or Objects. Here's what I mean:

public void checkMyValue(Object valueToCheck) {

  // ... null checking, other type checking, etc. Then...

  if (valueToCheck.getClass().isArray()) {
    // This will throw a ClassCastException for primitive arrays
    int length = ((Object[]) valueToCheck).length; 
    if (length == 0) {
        throw new IllegalArgumentException("Empty arrays are not allowed");
    }
  }
}

Is there any way to get the length of a primitive array without explicitly checking each primitive type?





C# Creating a List of Generic type using Reflection

I have been trying various combinations of answers I see online but I cannot quite get it working.

I have a PropertyInfo object as follows

Type myObj = something.GetType();
PropertyInfo other = myobj.GetProperty("People");

I then check if that property is a type of List<>

 other.PropertyType.GetInterface(typeof(IList<>).FullName) != null

What I cannot put together is, if this property called "People" is a List<Person> (where Person is some class in my solution), how do use reflection to create this object?

I need the mechanism to be Generic so that I can create an initialised empty list of and object.

I'm not sure what I'm missing to be able to do that. I'm may not be taking the right approach. Essentially, given that I detect a type of List or Enumerable of a given type, I need to return the initialised version of it. I hope this is clear enough for someone to help





ReflectionTypeLoadException because of build increment

I'm running a post-build script on my main application which increments the build number. Now my project searches for assemblies on startup and loads via reflection an instance of the plugin assembly I created in another project.

The plugin project references the main application. The build order is correct, of course. Nonetheless I get a ReflectionTypeLoadException because the plugin assembly is looking for the application version Build - 1 for some reason.

What is happening here? Since the plugin builds after the main application I assume it is referencing the freshly built version and not some older version. The increment is, like said, happening post-build, thus shouldn't influence anything.

Is this a Visual Studio internal bug or am I doing something wrong? I can't explain myself why this isn't working.





java reflection field type before upcasting

I have simple class

public class SomeService {

    private Number number = new Integer(0);
}

Is it possible to find out by means of java reflection the field type before upcasting?

I can just obtain Number type instead of Integer:

      Field field = MealService.class.getDeclaredField("number");    
      field.setAccessible(true);
      System.out.println("impl:"+field.getType());

Please advice.





Check if Property is List using Reflection in C#

I'm stuck at putting out the values of my objects at the moment. Some of them do have List<string>properties which causes trouble by using the ToString()Method. Here is the code I use in my base class to get the name and the value of the properties into a string.

public override string ToString()
    {
        string content = "";
        foreach (var prop in this.GetType().GetProperties())
        {
            if (prop.PropertyType is IList<string> && prop.GetType().IsGenericType && prop.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>)))
                content += prop.Name + " = " + PrintList((List<string>)prop.GetValue(this));
            else
            content += prop.Name + " = " + prop.GetValue(this) + "\r\n";
        }
        content += "\r\n";
        return content;
    }

    private string PrintList(List<string> list)
    {
        string content = "[";
        int i = 0;
        foreach (string element in list)
        {
            content += element;
            if (i == list.Count)
                content += "]";
            else
                content += ", ";
        }
        return content;
    }

Anyhow, the check if the propertie is a List does not work. This might be a dumb question and or a bad way to work with reflection but I'm kinda new to it and will appreciate any help to figure out what is going on.





Manually resolving assembly does not work as expected

Background:
I have an executable, which depends on a third party, let's call it library.dll. I have 2 separate installations of this dll: One for 32 bit and one for 64 bit. The library.dll needs to be loaded from a specific location, since it is not in GAC and neither in my executables folder. So I use the AppDomain.AssemblyResolve event to load library.dll from the correct path. My exe is compiled with "Any-CPU" flag set; note that this application can be started either in 32 bit environment or a 64 bit environment. In my VS project, I can only refer to one version of this library (either 32 bit or 64 bit) while doing the build.

Problem:
When I access the types within the library, it only works for the environment (32 or 64) of the referred library.dll. For example: If I have a reference to 64 bit version of the library.dll in my csproj, then my app loads the library.dll successfully and is able to access the types within that assembly, only in the 64 bit environment, but not in the 32 bit environment. In the 32 bit environment, I get a FileNotFound exception before accessing the types from library.dll. Also, my AssemblyResolve event does not get invoked in that case.

Here's what I understand so far:

  1. If I do not use a reference in the csproj, it will work fine, but that is not feasible, since all my type access will have to be done using reflection.
  2. When I add a reference (csc /reference) in my project, the compiler will auto-inject some code to load this dll before the usage. Apparently AppDomain.Current.AssemblyResolve event does not get fired while that happens.
  3. If I assume that the library.dll will be in the folder with the executable, then I don't need to implement AppDomain.Current.AssemblyResolve event to manually load the library.dll. In that case, my executable works fine in both 32-bit and 64-bit environments.

Conclusion & Questions:
It appears that the Framework is able to load the dll correctly irrespective of 32/64 bit environment, but I am not - so I am not loading the library.dll correctly. I am aware that a simple workaround to this would be to build 2 different versions of my exe, one for 32 bit with the 32 bit reference and one for 64 bit with the 64 bit reference. A side question is, why does the AppDomain.AssemblyResolve event not get fired when the dll is loaded based on c# auto-generated code to load the referenced dll. I have tried experimenting with using AppDOmain.ReflectionOnlyAssemblyResolve event with not much luck. I also wonder if AppDomain.TypeResolve event somehow plays a role in this situation.

Can you folks help me fill in the blanks in my knowledge about this process

Below is my sample code to demonstrate the issue. In my project, I have reference to a library.dll. Remember that I have a 32 bit version and a 64 bit version of this library available. You will have to build the application as 32 bit or 64 bit to simulate the 32/64 bit environments

using System;
using System.Reflection;
using System.IO;

class Program {
    static void Main(string[] args) {
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolver);
        Console.WriteLine(string.Join(", ", Enum.GetNames(typeof(MyEnum)))); // access some type from within library.dll
    }


    public static string GetLibraryPath() {
        return @"C:\Program Files (x86)\library";
    }

    private static Assembly AssemblyResolver(object sender, ResolveEventArgs args) {
        Assembly asmb = null;
        string splitchar = ",";

        // args.Name is like: "Library, Version=1.0.0.26173, Culture=neutral, PublicKeyToken=null"
        string module = args.Name.Substring(0, args.Name.IndexOf(splitchar));

        string dllPath = GetLibraryPath() + @"\" + module + ".dll";

        Console.WriteLine(String.Format("AssemblyResolver: About to load '{0}'", dllPath));

        try {
            if (File.Exists(dllPath))
                asmb = Assembly.LoadFrom(dllPath);

            if (asmb == null)
                Console.WriteLine("Unable to load assembly " + dllPath);
            else
                Console.WriteLine("Successfully loaded " + dllPath);
        } catch (Exception ex) {
            Console.WriteLine("Unable to load assembly: " + dllPath + "\n" + ex);
        }

        return asmb;
    }

}





Dynamically calculate average value no matter what type of values (integer, Timestamp, etc.)

I have a dynamic method GetAverage() using reflection to calculate an average value for a list of string values. The string values are dynamically converted to a type determined in ValueType. The type DataSet contains a List<string>:

public class AggregateController {     

    private List<DataSet> DataSets { get; set; }

    private Type ValueType { get; set; }

    public string GetAverage () {
        dynamic sum = Activator.CreateInstance(this.ValueType);

        this.DataSets.ForEach(x => {
            var mI = this.TransformInputValue(x[0]);
            return (dynamic)mI.Invoke(this, new object[] { value });
        });

        return sum.Average().ToString();              
    }

    private dynamic TransformInputValue (string value) {
        try {
            var mI = this.ValueType.GetMethod("Parse", new Type[] { typeof(string) });
            return (dynamic)mI.Invoke(this, new object[] { value });
        } catch {
            return null;
        }
    }
}

This method does everything perfectly when the given values are numeric values. Now I want to achieve dynamically calculating average values for timestamp values with the same method. The problem is that there is no Average() extension method for TimeStamp objects and I do not mean to additionally implement a condition checking for timestamp values like this:

if (this.ValueType == typeof(TimeStamp)) {
    //do stuff to calculate TimeStamp average.
} else {
    return sum.Average().ToString();
}

Is there a way to dynamically react to types like TimeStamp which have no Average() extension method?





Ability to access Android application from included AAR library

I've included an aar library in my Android app. What should I do to prevent it from accessing my app's classes, resources, shared preferences, ... on runtime via reflection? Is there another way besides reflection?





Golang set struct field using reflect

I am currently doing the following

func Test(controller interface{}) {
    controllerType := reflect.TypeOf(controller)
    controllerFunc := reflect.ValueOf(controller)
    controllerStruct := reflect.New(controllerType.In(0))
    for i := 0; i < controllerStruct.Elem().NumField(); i++ {
        if controllerStruct.Elem().Field(i).Kind().String() == "ptr" {
            controllerStruct.Elem().Field(i).Set(
                reflect.New(
                    controllerStruct.Elem().Field(i).Type(),
                ).Elem(),
            )
        }
    }
    controllerFunc.Call([]reflect.Value{
        controllerStruct.Elem(),
    })
}

Using the following function call

Test(controllers.Test.IsWorking)

type Test struct {
    Name string
    H    *Hello
}

type Hello struct {
    Friend string
}

func (t Test) IsWorking() {
    log.Println(t.H)
}

t.H is always nil even tho I am setting it on the for loop. Also I am not sure if this is the correct way to make this since what about if Hello struct contains another pointer to a struct. Is there a better method to achieve what I am trying to do and why is t.H nil if I am setting it up





mardi 26 juillet 2016

Is it possible to replace a C# method in another process at runtime?

I've seen that through reflection you can call and even replace internal and private methods of classes in other assemblies within your own process.

(I love LogMan's answer to this related question: Dynamically replace the contents of a C# method?)

I would like to dynamically replace (wrap) a method of a loaded .NET assembly in another (native) process in the system, specifically ehrecvr.exe.

Is this possible? Alternatively, is it possible to add an extra assembly to load when that binary is run, which would then be in-process for the method replacement?





Call a specified action from a validation attribute

I am currently creating an attribute similer to the existing "Remote" attribute. The client side validation is stright forward with javascipt calling an action to check (againt our database) that the input is valid. The problem is when it comes to server side validation I cannot work out how I can call the action. The "Remote" attribute is no help since "Does no server-side validation"

No client side code is show since thats working fine.

The attribute

[AttributeUsage(AttributeTargets.Property)]
public class AjaxValidation : Attribute, IModelValidator {

    private readonly string _action;
    private readonly string _area;
    private readonly string _controller;

    public AjaxValidation(string action, string controller = null, string area = null) {
        _action = action;
        _area = area;
        _controller = controller;
    }

    public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context) {

        List<ModelValidationResult> result = new List<ModelValidationResult>();

        //Need to call the action and check the result here

        //Create the controller with reflection?

        //Call the method with reflection?

        if(false was returned) {
            result.Add(new ModelValidationResult("", "{0} is invalid"));
        }

        return result;

    }
}

A model showing it's usage

[AjaxValidation ("Validate", "Home", "Examples")]
public string Value{ get; set; }

and an action that model would call (Also used by the client side)

public ActionResult Validate(string id) {

    if (id.Length == 3) {
        return Json(new { Success = true });
    } else {
        return Json(new { Success = false });
    }

}





Get struct from function type

I currently have the following code

func (r *Router) Get(path string, controller interface{}) {
    ...
    t := reflect.TypeOf(controller)
    ...
}

That is called doing the following

Route.Get("/", controllers.Test.IsWorking)

The second argument is basically this

type Test struct {
    *Controller
    Name string
}

func (t Test) IsWorking() {

}

type Controller struct {
    Method   string
    Request  *http.Request
    Response http.ResponseWriter
    Data     map[interface{}]interface{}
}

What I want is to get what struct the function passed on the Router.Get needs so I can create that struct using reflect and set the fields manually (pass the main Controller)

I am not sure how to achieve this... TypeOf returns

func(controllers.Test)

I cant use Eleme() since the struct is not expecting a pointer... how should I approach this. The reflect package docs arent very clear on the usage





Inferring String value type in Groovy

I have a situation where I will be given a String and I need to determine what Class<?> best suits its value given the following constraints:

  • If the String is (ignoring case) equal to "true" or "false", it's a Boolean
  • Else, if the String is an integral number with no decimal point, it's an Integer
  • Else, if the String is a number, it's a Double
  • Else, if the String matches the date time format YYYY-MM-DD hh:mm:ss.sss, then its a Java Date
  • Else it's just a String afterall

My best attempt is nasty and involves a lot of nested try/catch blocks:

// Groovy pseudo-code
Class<?> determineValueType(String value) {
    Class<?> clazz
    if(value.equalsIgnoreCase('true') || value.equalsIgnoreCase('false')) {
        clazz = Boolean
    } else {
        try {
            Integer.parse(value)
            clazz = Integer
        } catch(Exception ex1) {
            try {
                Double.parse(value)
                clazz = Double
            } catch(Exception ex2) {
                try {
                    Date.parse('YYYY-MM-DD hh:mm:ss.sss', value)
                    clazz = Date
                } catch(Exception ex3) {
                    clazz = String
                }
            }
        }
    }

    clazz
}

Are there any Groovier ways of accomplishing this, perhaps something endemic to some obscure Groovy reflection API?





Generic List To DataTable

I wrote something maybe someone can learn from:

public DataTable BulkUploadToSqlServer<T>(List<T> ListToInsert, string DataTableName)
    {
        Type typeParameterType = typeof(T);
        var attributes = typeParameterType.GetProperties();

        var dt = new DataTable(DataTableName);

        for (int attribute = 0; attribute < attributes.Length; ++attribute)
            dt.Columns.Add(attributes[attribute].Name, attributes[attribute].PropertyType);


        for (int obj = 0; obj < ListToInsert.Count; ++obj)
        {
            DataRow dr = dt.NewRow();
            for (int attribute = 0; attribute < attributes.Length; ++attribute)
                dr[attributes[attribute].Name] = ListToInsert[obj].GetType().GetProperty(attributes[attribute].Name).GetValue(ListToInsert[obj], null);
            dt.Rows.Add(dr);
        }
        return dt;
    }

we can always use FastMember and just write:

DataTable table = new DataTable();
        using (var reader = ObjectReader.Create(ListToInsert))
        {
            table.Load(reader);
        }

I'm writing this to all of you that want to have some more experience in reflection in windows environment.

you can always use FastMember solution, I don't know how much you'll be able to learn from it.

good luck.





Is there a way to type-cast a Scala object using reflection?

I am using reflection to create Scala objects. I don't have ready access to 'T', to type-cast an object like one normally would like this:

def makeOne[T](o:Object) = o.asInstanceOf[T]

I do have a universe.Type tho. Earlier in my processing I do something like this:

def analyze[T](o:Object)(implicit tt:TypeTag[T]) = {...}

I save tt.tpe, so much later when I'm creating an object of type T, I've lost the 'T' but I still retain tt.tpe.

Is there any way I can use this universe.Type to type-cast my object without having to need 'T', as in .asInstanceOf[T]?

(BTW, I can create the object using reflection just fine...Its just that the created object doesn't know its type. It's just thinks its an Any.)





How can I retrieve data from DisplayAttribute of interface?

I have the following code:

public interface TestInterface
{
    [Display(Name = "Test Property")]
    int Property { get; }
}

class TestClass : TestAttribute
{
    public int Property { get; set; }
}

Note, that the property of interface is marked with DisplayAttribute. When I am trying to get the value from attribute, the following code samples does not works.

First sample: direct access to property of class.

var t = new TestClass();

var a = t.GetType().GetProperty("Property").GetCustomAttributes(true);

Second sample: cast object to interface and get access to property.

var t = (TestInterface)new TestClass();

var a = t.GetType().GetProperty("Property").GetCustomAttributes(true);

But when I am passing object as a model for mvc view and calling @Html.DisplayNameFor(x => x.Property) it returns the correct string "Test Property".

View

@model WebApplication1.Models.TestInterface
...
@Html.DisplayNameFor(x => x.Property)

renders as

Test Property

How can I achieve the same result with code on server side? And why I can not do it with simple reflection?





How can I know the last object when I reflect?

I have a DTO like this,

ADto{
  BDto bDto;
  Cto cDto;
}

BDto{
  String a1;
  String b1;
  int b1;
}

CDto{
  String a2;
  String b2;
  int b2;
}

When I use reflect,I want to get the BDto and CDto in ADto Object.Code like this:

 for (Field field : aObj.getClass().getDeclaredFields()) {
            try {
                Object fieldValue = field.get(object);
 //todo  how to collect all String value  in `BDto` and `CDto` of aObj
                if (fieldValue instanceof String) {
                    shouldCheckFieldValues.add((String) fieldValue);
                }
            } catch (Exception e) {
                logger.error("some error has happened when fetch data in loop", e);
            }

        }
    }

I want to collect all String value in BDto and CDto of aObj?How can I achieve this? Or how can I know the field which I have to recursive traversal with no hard code?





Laravel 5.2 RefectionException

A newbie question ...

To open the first page (index) I have the following in a GamesController:

 public function index()
{
    //show a listing of games
    $games = Game::all();
    return view('index',['games'=> $games]);
}

which works fine. I have at the top of the controller

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Game;

The model is simply

namespace App;

use Illuminate\Database\Eloquent\Model;

class Game extends Model
{
    //
}

In my index page I have a simple list from the db with an edit button which has the code:

<a href="" class="btn btn-default">Edit</a>

In my controller have the following:

public function edit(Request $request)
        {
            $games = Game::find($request->id);
            return view('edit',['games'=>$games]);
        }

but when I press the edit button I get

enter image description here





lundi 25 juillet 2016

Google Directory API : getting UserEmail object using java client

Google Directory User object returned by Google has name attribute rightly as UserName object but emails attribute is of type ArrayList of E' and email properties are present as an ArrayMap in the first member of this list instead of coming as aUserEmail' object strangely.

In my case, I get to decide the type of attribute only run-time and hence I'm using Java Reflection as below.

String outerGetter = "get" + outerParam;

List<Object> outerValues = (List<Object>)ReflectionUtils.get(user, outerGetter);

if(outerValues == null){
    return null;
}
String innerGetter = "get" + upperFirstLetter(attrName.substring(firstDotIndex + 1));
for(Object outerValue: outerValues){
    JSONObject jo = new JSONObject();
    Object innerValue = ReflectionUtils.get(outerValue, innerGetter);
    if(innerValue == null){
        return null;
    }
    jo.put(scimAttribute.subName, innerValue);
    ja.put(jo);
}

ReflectionUtils.get(user, method) basically executes method of user and return Object type.

For name property : outerGetter is getName and innerGetter is say getFamilyName and it works fine.

But for emails property : outerGetter is getEmails and innerGetter is getAddress and it gives NoSuchMethodException: com.google.api.client.util.ArrayMap.getAddress(). getAddress() is part of UserEmail object and hence this exception I guess. Can anyone tell me why I'm not getting UserEmail object in the first place?.

I'm new to Reflection as well as Google Directory APIs. Any help is appreciated.





Can reflection change the state of an object?

I read the following article about reflection in Java:

http://ift.tt/2arCozO

In it, the author describes how to change the values of an object's fields through reflection. He explains how to do it even if the field has private access.

I while back, I read Joshua Block's book: "Effective Java". There, he says that, in order to prevent unsafe access to an object's fields, methods, etc, whenever possible, we should give fields and methods the most restrictive modifier (ie. private whenever possible, public or protected if it is part of the exposed api).

My question is the following:

Why bother designing your classes to not expose sensible information if it can be accessed through reflection anyway?

(Actually, I am asking for the piece of information that I am missing to understand this topic)





Creating a Func

After much research and searching on SO; I've failed to find an answer that encompasses my specific situation. I wish to add modding capabilities to my project; currently I use a 3rd-party C# API which can convert scripts written in a particular interpreted language (specifically the functions in these scripts) into C# delegates.

Is there a way to wrap all of the delegates I get from the 3rd party API, into the a generic Func Delegate? My thoughts (in code) follow...

//The goal signature for all 'imported' delegates
public delegate object GenericSignature(object[] args);

//A fictional example...
public class Program
{
    public static void Main()
    {
        GenericSignature desiredFunc = GenerateFromArbitraryMethod(Program.FictionalArbitraryMethod);
        object retVal = desiredFunc(1, new object(), "If only this worked");
    }

    public static FictionalArbitraryMethod(int num, object stuff, string name) { //code from mod author would be here }
}

//Attempt #1
//If my assumptions about Delegate.CreateDelegate() is correct, this probably will not work... 
public GenericSignature GenerateFromArbitraryMethod(Delegate d) {
    MethodInfo mInfo = d.Method;
    return (GenericSignature) Delegate.CreateDelegate(typeof(GenericSignature), mInfo);
}

//Attempt #2
public GenericSignature GenerateFromArbitraryMethod(Delegate d) {
    MethodInfo mInfo = d.Method;

    //seems a bit... better?; I can do some validation, but how do I actually call the 
    //function represented by MethodInfo since it's signature is arbitrary?
    return delegate(object[] args) {

        ParameterInfo[] pInfo = mInfo.GetParameters();
        if(args.length != pInfo.length) {
             throw new Exception("Argument count does not match");
        }

        for(int i = 0; i < args.length; i++) {
             if(pInfo[i].ParameterType != args[i].GetType()) {
                 throw new Exception("Incorrect Type for argument");
             } 
        }

        //At a loss of how to do the following; fake psuedo-code follows
        /*
        Foreach(object currentArg in arg) {
           d.AppendArgAndCast(currentArg); 
        }
        return d.Call();

        or...

        return d(EachOrUnpackAndCast(args));
        */

    };
}

Apologies if there are any errors in the syntax; I'm mainly trying to get across the concept of what I'm trying to achieve. Some additional notes:

EDIT: 1. My project is targeting .NET 2.0 (and possibly... a subset of .NET 3.5?) Not 100% sure of what is supported in Unity.

  1. It is ok if any suggested solution is 'slow/heavy' due to heavy use of reflection; as long as I can generate a delegate, which I can cache and just call many, many times (to amortize the initial delegate creation cost)




Is there any way I can get a Type by any alias for a type?

For example, "int" and "Int32" refer to the same type in C#.NET, but when I run var t = Type.GetType("int"); for example, no matching type is found.

The reason I'm wondering is because I'm writing tests that involve extracting the types from URL patterns like "foo/bar/{username:string}/{page:int}".





Is there an handy way to figure out whether an Object implements

I'm trying to figure out if there is any builtin routines or classes in the .NET framework that could provide a convenient way to test whether a collection implements among the following interfaces and hence hook to the relevant events, if any:

  • IEnumerable
  • IList
  • ICollection
  • IBindingList
  • IEnumerable <T>
  • IList <T>
  • ICollection <T>
  • IRaiseItemChangedEvents
  • INotifyCollectionChanged

Mostly for data-binding purposes...

I can go with a lot of reflections (e.g. IsAssignableFrom) but since it seems to be a pretty common scenario, I was wondering if there was anything already done in that regard.





dimanche 24 juillet 2016

How do I convert this non-reflection code into reflection code

I want to convert this to reflection:

CraftServer serv = (CraftServer)p.getServer();

(and by convert to to reflection I mean, showing and explaing all the reflection you use to write code that does the same thing that the code above does, like using Class.cast() and whatnot)





samedi 23 juillet 2016

java - So I get the NullPointerException, how can I fix it?

So I'm just started to learn Java in school for like a month now, and I have this homework to make a simple Twitter-based social network. But I haven't learned database yet so we just making a simple database in the program.

Now the part where I get the error is that I instead of using switch, I used Reflection to call the methods in another class. And I get the NullPointerException error. I have read What is a NullPointerException, and how do I fix it? but I don't know how to fix it.

JavatterController.java

package jp.ac.kcg.java1;

public class JavatterController {
Javuser currentUser;
Database db;

public JavatterController(int index) {
    db = new Database();
    currentUser = db.getUser(index);
    System.out.println(currentUser.getUserIdWithAt() + " has logged in!");
}


public void tw(String tweet) {
    Tweet newTweet = new Tweet(tweet, currentUser.userId);
    db.insertTweet(newTweet);
    System.out.println(currentUser.getUserIdWithAt() + " just tweeted " + tweet);
}

Javatter.java

try {
                // load the AppTest at runtime
                Class<?> cls = Class.forName("jp.ac.kcg.java1.JavatterController");
                Object obj = cls.newInstance();
                // call the printItString method
                Method method = cls.getDeclaredMethod(input[0], paramString);
                method.invoke(obj, new String(input[1]));
            } catch(Exception ex) {
                ex.printStackTrace();
            }

And this is the error I got

@manofsteel > tw lol
@manofsteel > java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at jp.ac.kcg.java1.Javatter.main(Javatter.java:48)
Caused by: java.lang.NullPointerException
    at jp.ac.kcg.java1.JavatterController.tw(JavatterController.java:39)
    ... 5 more

So where did I do wrong and how can I fix it? Thanks in advance.





Is it possible to look up all name alias of a given type (e.g. "int" versus "Int32")?

I've been writing unit tests to verify the validity of MVC routes. For example,

[Route("foo/bar/{id:int}")]
public IHttpActionResult SomeAction(int id)
{
   // ... 
}

would be valid but

[Route("foo/bar/{id:List<string>}")]
public IHttpActionResult SomeAction(int id)
{
   // ... 
}

or

[Route("foo/bar/{buzz:int}")]
public IHttpActionResult SomeAction(int id)
{
   // ... 
}

wouldn't.

But the problem is that I'm getting false negatives because, in the first example above, when I check that {int:id} in the route matches a parameter in the action method, the name of the type in the parameter is Int32 via reflection and I don't know how to make my test know that Int32 is the same as int. Is there a way?





Why can't I get the event handler of a LinkButton's event using reflection?

I want to access the event handler of a LinkButton's Command event, but the in the snippet bellow fieldInfo is null.

LinkButton button = new LinkButton();
button.Command += (s, e) => { };
Type type = button.GetType();
EventInfo[] eventInfos = type.GetEvents(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (EventInfo eventInfo in eventInfos)
    if (eventInfo.Name == "Command")
    {
        // fieldInfo is null
        FieldInfo fieldInfo = eventInfo.DeclaringType.GetField(eventInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
        Delegate delegates = (Delegate)fieldInfo.GetValue(button);
        foreach (Delegate handler in delegates.GetInvocationList())
        {
            eventInfo.RemoveEventHandler(button, handler);
            // or
            eventInfo.AddEventHandler(button, handler);
            // or do whatever with handler
        }
    }

Code snippet was inspired from this.

Why is fieldInfo null ?

Is there another way to get the event handler of a LinkButton's Command event ?

Also Hans Passant sollution does not work on LinkButton using Command as the field name.





How I reflect List

I have some questions when I reflect genericType.First of all,I have a class declaration like this:

public class JoyPageWebDTO<T> {
    private int recordCount;
    private int pageSize;
    private int pageIndex;
    private List<T> records;
}

And T is:

public class AuditSpuWebDTO implements Serializable {
    private String indications;
    private String forbidden;
    private int shopID;
    private String shopName;
    private String city;
    private Date updateTime;
    private int auditStatus;
    private String auditContent;
}

The result of JoyPageWebDTO after request like this: [http://ift.tt/2a3lHeT]

The question is how can I get the T(AuditSpuWebDTO) from JoyPageWebDTO? I want's get the value of AuditSpuWebDTO.I wrote some code as following to deal this,however,failed!

public static void reflect(Class<?> clazz) {
    for (Field field : clazz.getDeclaredFields()) {
        //get the static type of the field
        Class<?> fieldType = field.getType();
        //if it's String,
        if (fieldType == String.class) {
            // save/use field
        }
        //if it's String[],
        else if (fieldType == String[].class) {
            // save/use field
        }
        //if it's List or a subtype of List,
        else if (List.class.isAssignableFrom(fieldType)) {
            //get the type as generic
            ParameterizedType fieldGenericType = (ParameterizedType) field.getGenericType();
            //get it's first type parameter
            Type type = fieldGenericType.getActualTypeArguments()[0];
            Class<?> fieldTypeParameterClazz;
            if (type instanceof ParameterizedType) {
                fieldTypeParameterClazz = (Class<?>) ((ParameterizedType) type).getRawType();
            } else if(type instanceof TypeVariable){
                //todo how to get the class????
            }else{
                fieldTypeParameterClazz = (Class<?>) type;
            }
            //if the type parameter is String,
            if (fieldTypeParameterClazz == String.class) {
                // save/use field
            }
        }
    }
}

When I reflect about the generic type:T from List,the type of the result is TypeVariable,how can I get the Class<?> from TypeVariable? The todo which I mark is the key crucial problem I have.





vendredi 22 juillet 2016

How do I access a namespaced class constant in PHP using a variable for the class name?

I have the following.

my class
<?php
namespace app\models;    
use BingAds\CustomerManagement\CustomerManagementServiceSettings;

and

api class
namespace BingAds\CustomerManagement
{
    final class CustomerManagementServiceSettings
    {
        const SandboxEndpoint = 'http://ift.tt/2ai48dK';

How do I access the constant using a variable for the class name? It works for instantiating the class directly, but I can't access or instantiate the class when it is a variable.

new CustomerManagementServiceSettings();
$serviceSettingsClass = 'CustomerManagementServiceSettings';
$serviceSettingsClass::SandboxEndpoint; # line 80

Gives

PHP Fatal error: Class 'CustomerManagementServiceSettings' not found in /cygdrive/c/Users/Chloe/workspace/bestsales/models/BingAds.php on line 80

This question did not help.

In Java I could use

Class c = CustomerManagementServiceSettings.class
String se = (String) c.getField("SandboxEndpoint").get(null);





how spring does component scan

I want to know how exactly spring has achieved component scanning ability. I want to implement same without any external libraries such as google reflection or spring but with plain java code.





Java - Dynamic instantiation of new objects

I'm a fairly-new developer in the process of writing a Java application that needs to create objects dynamically. These objects are unique and need to be uniquely referenced, but are all part of the same generic data class with the same attributes. Each of these attributes is a String, and they are:

  • the value of the data
  • the source of the data
  • a reference interfaceCode that enables me to place the data in the correct location in an interfacing system
  • a reference parent that ties the data object to a parent object representing a data classification used in the interfacing system

And getters/setters for each. Values for each of those attributes is set using setters called in the public constructor with two arguments passed in. Here is a code sample:

class DataObject {

private String value, source, interfaceCode, parent;

    public DataObject(String arg1, String arg2) {

    setValue(arg1);
    setSource(arg2);
    setInterfaceCode(arg2);
    setParent(arg2);

    }

    //setters/getters here
    /
    /
    /
}

The issue I'm running into is determining how to create these objects uniquely and dynamically - I have input code that reads a data source document and pulls out data I want. If it finds data of a certain source type (which occur once per document), it needs to create a new Data Object and assign the values to that. This reference is intended to be stored in a HashMap<String,DataObject with the String describing the data source set as a key and the DataObject reference being the value assigned. This is all run in a different Class, as you can see below:

class DataParser {

private String value, source;

    public DataObject DataParser() {

        if (value != null && source != null) {

             DataObject newData = new DataObject(value, source);

        }

        return newData;

    }

    //data setter/getter here to grab data from data source and provide access
    /
    /
    /
}

So, I've read a whole bunch of StackOverflow posts/questions on this and I'm still coming up short. From many of the answers, I thought this problem might require reflection. However, I'm a little overwhelmed by the topic and not really sure if this is the correct route.

My concern is that, with my original code, that DataObject reference from newData will simply be overwritten each time I instantiate a new DataObject. Ideally, I would have it instantiate a new Object with a variable name equivalent to the value of source, but this is entirely unnecessary - what matters is the reference.

Can someone point me in the right direction regarding this problem?





Throw exception indicating variable name upon InvalidOperationException upon Nullable->Value

I have a large set of Nullable<> variables as input to a somewhat complex algorithm, some of which shouldn't be null in certain contexts. At the moment, I'm relying on the InvalidOperationException thrown upon Nullable<>.Value when I hit that wall. The client app of my algo thereby knows by that exception that something is missing, but doesn't know what.

I'm looking for a way to catch that exception and get back to the name of the variable that caused it (those variables have human-readable names), so my client app can get informed of it. I'm thinking Reflection is the only way, but where do I start ?





C# FieldInfo reflection alternatives

I am currently using FieldInfo.GetValue and FieldInfo.SetValue quite a lot in my programm, which is significantly slowing up my programm.

For PropertyInfo I use the GetValueGetter and GetValueSetter methods so I only use reflection once for a given type. For the FieldInfo, the methods don't exist.

What is the suggested approach for FieldInfo?





Configuration Interface to use with Framework

I'm currently developing a framework where I'll provide an Interface that the user should implement in his application for configuration purposes. The user should ne able to implement a getTargetUsername() that will be used in the framework side.

What I'm trying to achieve a is pretty much what Togglez do:

public class MyTogglzConfiguration implements TogglzConfig {

    public Class<? extends Feature> getFeatureClass() {
        return MyFeatures.class;
    }

}

My problem is that I'm struggling to find how should I lookup for the class that is implementing my configuration interface. And call the getTargetUsername() method inside the framework.


What I've tryed so far:

I'm currently trying to do the trick using Reflections, but I'm not sure this is the right approach, since I don't know if this is looking only inside my framework package or it will search inside a prject that add it as a dependency.

Reflections reflections = new Reflections();
Set<Class<? extends FrameworkConfig>> configurations = reflections.getSubTypesOf(FrameworkConfig.class);

//Getting the Class thats is implementing here
Object c = configurations.toArray()[0];

I'm being able to get the right Class with the above code but I acctually can't call getTargetUsername().





Field getter/setter with expression tree in base class

Following the examples on this post and its follow-up question, I am trying to create field getters / setters using compiled expressions.

The getter works just great, but I am stuck the setter, as I need the setter to assign any type of fields.

Here my setter-action builder:

public static Action<T1, T2> GetFieldSetter<T1, T2>(this FieldInfo fieldInfo) {
  if (typeof(T1) != fieldInfo.DeclaringType && !typeof(T1).IsSubclassOf(fieldInfo.DeclaringType)) {
    throw new ArgumentException();
  }
  ParameterExpression targetExp = Expression.Parameter(typeof(T1), "target");
  ParameterExpression valueExp = Expression.Parameter(typeof(T2), "value");
  //
  // Expression.Property can be used here as well
  MemberExpression fieldExp = Expression.Field(targetExp, fieldInfo);
  BinaryExpression assignExp = Expression.Assign(fieldExp, valueExp);
  //
  return Expression.Lambda<Action<T1, T2>> (assignExp, targetExp, valueExp).Compile();
}

Now, I store the generic setters into a cache list (because of course, building the setter each time is a performance killer), where I cast them as simple "objects":

 // initialization of the setters dictionary
 Dictionary<string, object> setters = new Dictionary(string, object)();
 Dictionary<string, FieldInfo> fldInfos = new Dictionary(string, FieldInfo)();
 FieldInfo f = this.GetType().GetField("my_int_field");
 setters.Add(f.Name, GetFieldSetter<object, int>(f); 
 fldInfos.Add(f.Name, f); 
 //
 f = this.GetType().GetField("my_string_field");
 setters.Add(f.Name, GetFieldSetter<object, string>(f); 
 fldInfos.Add(f.Name, f); 

Now I try to set a field value like this:

 void setFieldValue(string fieldName, object value) {
      var setterAction = setters[fieldName];
      // TODO: now the problem => how do I invoke "setterAction" with 
      // object and fldInfos[fieldName] as parameters...?
 }

I could simply call a generic method and cast each time, but I am worried about the performance overhead... Any suggestions?





How can I get an element of a HashSet with reflection?

I'm trying to get the type of an array elements. I got something like this:

Set<Foo> mySet = new HashSet<Foo>();

I have to take via reflection the 'Foo' as a String. I tried something like this:

if (className.equals("java.util.HashSet")){
        Object arrayElement = Array.get(value, 0);
        isComplex = isComplex(field, arrayElement);
}

Array.get() is only for ArrayList and there isn't any HashSet.iterator()as Util

Thanks!





java reflection :Avoid warning unchecked call to getConstructor(Class?> ...) as a member of the raw type Class

I have read this post

java: unchecked call to getConstructor(java.lang.Class<?>...)

for (Map.Entry<String, Class> entry : connectionRepository.entrySet()) {
            if (/*someconditionhere*/) {
                try {
                    cwsConnection = (CWSConnection)entry.getValue().getConstructor().newInstance();
                    break;
                } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                    logger.error("Could not Create instance of CWSConnection for site version:\"{}\" Error:\"{}\"", entry.getKey(), e.getMessage(), e);
                } 
            }
        }

While compiling this piece of code I am getting a warning

warning: [unchecked] unchecked call to getConstructor(Class...) as a member of the raw type Class

I just wanted to get the default constructor of CWSConnection, therefore, I should not pass any parameters to getConstructor(Class...) method. Is there any better approach to get the default constructor(The one without arguments)

(I know @SupressWarning annotation will suppress this warning.)





Dynamically build an object from a strongly typed class using C#?

Currently, am adding the properties and values to the object manually like this example and sending to Dapper.SimpleCRUD to fetch data from Dapper Orm.

object whereCriteria = null;
whereCriteria = new
{
    CountryId = 2,
    CountryName = "Anywhere on Earth",
    CountryCode = "AOE",
    IsActive = true
};

The following class should build the object in the above mentioned format and return the ready-made object.

public static class WhereClauseBuilder
{
    public static object BuildWhereClause(object model)
    {
        object whereObject = null;
        var properties = GetProperties(model);

        foreach (var property in properties)
        {
            var value = GetValue(property, model);

            //Want to whereObject according to the property and value. Need help in this part!!!
        }

        return whereObject;
    }

    private static object GetValue(PropertyInfo property, object model)
    {
        return property.GetValue(model);
    }

    private static IEnumerable<PropertyInfo> GetProperties(object model)
    {
        return model.GetType().GetProperties();
    }
}

This function WhereClauseBuilder.BuildWhereClause(object model) should return the object in expected format (mentiond above). Here is the implementation of how I would like to use.

public sealed class CountryModel
{
    public int CountryId { get; set; }
    public string CountryName { get; set; }
    public string CountryCode { get; set; }
    public bool IsActive { get; set; }
}

public class WhereClauseClass
{
    public WhereClauseClass()
    {
        var model = new CountryModel()
        {
            CountryCode = "AOE",
            CountryId = 2,
            CountryName = "Anywhere on Earth",
            IsActive = true
        };

        //Currently, won't return the correct object because the implementation is missing.
        var whereClauseObject = WhereClauseBuilder.BuildWhereClause(model);
    }
}





How to identify a derived class and launch its member from the base class through reflection

I have a base class:

abstract class ClassPlugin
{   
    public ClassPlugin(eGuiType _guyType)
    {
        GuiType = _guyType;
    }

    public eGuiType GuiType;
}

then I have various derived classes, one of them being this

class ClassIO : ClassPlugin
{
    public ClassIO(eGuiType _guyType, eIoType _ioType) : base(_guyType)
    {
        GuyType = _guyType;
        ioType = _ioType;
    }

    eIoType ioType; 
    public enum eIoType { UKNOWN, READ, WRITE, MONITOR }
    public override void Action(){...}
}

so now when launching my application I use that code:

public static List<Type> FindAllDerivedTypes<T>()
{
    return FindAllDerivedTypes<T>(Assembly.GetAssembly(typeof(T)));
}

public static List<Type> FindAllDerivedTypes<T>(Assembly assembly)
{
    var derivedType = typeof(T);
    return assembly
            .GetTypes()
            .Where(t =>
                    t != derivedType && derivedType.IsAssignableFrom(t)).ToList();

}

finally I use it with

var output = FindAllDerivedTypes<ClassPlugin>();
foreach (var classType in output)
{
    if (classType.Name == "ClassIO")
    {
        foreach (var item in classType.GetMembers())
        {
            ????        
        }
    }
}

so what I need to do is [pseudocode to be put where the ??? are]

bool IsMonitorType = false;
if(item.member == eIoType && item.Value == eIoType.MONITOR)
{
    IsMonitorType == true;
    break;
}

and then

if(item.member.Name "Action")
{
    item.member.execute();
}

so in short I have to:

  1. identify the instance type throgh eIoType

  2. if ioType == MONITOR execute its Action routine

Thank you for any help





jeudi 21 juillet 2016

How to fetch value of an enum present in an inner class through Reflection

Hello all I am trying to access the value of an enum present in an inner class as shown below ,but what i am getting is not the value but the key . The need of my application is I have to access this value through reflection .

public class Test{
 static class TwelveByTwentyFour {
     public static enum BET_TYPE_NAME {
         Direct12(12),AllOdd(12),AllEven(12), First12(12), Last12(12);

    private int value;
    BET_TYPE_NAME(int value){
                this.value = value;
            }

            public  int getValue() {
                return value;
            }
            public void setValue(int value) {
                this.value = value;
            }
    }

 }
 public static String getBetTypeLength(String gameName,String betType) throws ClassNotFoundException, IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException{
        return Class.forName(Test.class.getCanonicalName()+"$"+gameName+"$"+"BET_TYPE_NAME").getDeclaredField(betType).get(null).toString();
    }
 public static void main(String[] args) throws IllegalArgumentException, SecurityException, ClassNotFoundException, IllegalAccessException, NoSuchFieldException {
    System.out.println(getBetTypeLength("TwelveByTwentyFour", "AllEven"));
}

}

On doing this I am getting "AllEven" as output instead of "12" . can anyone please help me by telling me that how can I get the value.Thanks in anticipation.





Removing a KeyValuePair of an IReadOnlyDictionary in runtime?

Is there a way to remove a KeyValuePair of an IReadOnlyDictionary at runtime using reflection? I do have key value.

Thanks





using generic class as a list

I want to declare List<clz> in the following code snippet. But it says clz cannot be resolved to a type. Any idea why? I'm new to java reflections.

Method method = user.getClass().getMethod(outerGetter);
Class<?> clz = method.getReturnType();
List<Class<?>> outerValues = (List<Class<?>>)ReflectionUtils.get(user, outerGetter);

Any help is appreciated, thanks!





How to access classes of another java process using reflection?

I wants to access the classes and its data member values of process1 from the process2 using reflection.

*Java process1
*Java process2

How could i do it?





Implement Same Function for different Generic Types with Reflection

I'm currently working on a Solution to compare two elemts of the same object with eachother. Code looks like this:

public double Compare(Data o)
    {
        double same = 0;
        double different = -1;

        foreach (var prop in o.GetType().GetProperties())
        {
            if (prop.GetValue(o) == prop.GetValue(this))
                same++;
            else
                different++;
        }            
        return (same / (different + same)) * 100;
    }

Data is an example for an implementation of the IData Interface, created by my own. Since there are more types of different datastructures, there are identical implementations of the function in each and every object, that implements the particular interface. Now, this kinda disturbes me because it seems to be stupid to have the exact same lines of code in different classes.

Is there any chance, that I can use one method for all of my different classes and still work with reflection? I thought about the szenario quite a while and just couldn't figure out how to refere to the correct "this" reference. Only idea I got is, to write an helper class with two parameters for the function and call that helper method in the specific data call implementation. Code would look like this:

class CompareHelper
{
     public double Compare(Data o, Data callingObject)
     {
        double same = 0;
        double different = -1;

        foreach (var prop in o.GetType().GetProperties())
        {
            if (prop.GetValue(o) == prop.GetValue(callingObject))
                same++;
            else
                different++;
        }  
        return (same / (different + same)) * 100;
     }
 }

Any other recommendations?

Thanks in advance!





How do you remove a Java Annotation at Runtime (probably using Reflection)?

We are building a tool (for internal use) that only works if the javax.persistence.GeneratedValue annotation is removed from our source code (we are setting the Id in the tool, which is rejected due to the GeneratedValue annotation)... but for normal operations, we require this annotation.

How do you remove a Java Annotation at Runtime (probably using Reflection)?

This is my class:

@Entity
public class PersistentClass{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  // ... Other data
}

This is what I would like to be able to change it to, at runtime:

@Entity
public class PersistentClass{
  @Id
  private long id;

  // ... Other data
}

Thanks!





Getting a method with an action via reflection (EntityFramework)?

Ok, so I'm trying to access the .Map function in a FluentApi EF6 setup. Here's what I've got so far:

// First, get our DbModel.Entity<> method, and make it a generic of the dbSetType Type variable
MethodInfo dbModelMethodInfo = typeof(DbModelBuilder).GetMethod("Entity").MakeGenericMethod(dbSetType);

// Now, since we'd have normally chained this, with reflection we want to take the return type 
// from dbModelMethodInfo and grab the ToTable Method, specifically the (string, string) constructor
MethodInfo entityTypeConfigInfo = dbModelMethodInfo.ReturnType.GetMethod("ToTable", new[] { typeof(String), typeof(String) });

MethodInfo[] methodInfoArray = dbModelMethodInfo.ReturnType.GetMethods(BindingFlags.Public | BindingFlags.Instance);

// We also need to grab the Map if it's changed
MethodInfo entityTypeMappingInfo = dbModelMethodInfo.ReturnType.GetMethod("Map", new[] { typeof(Action) });

Long story short, I'm remapping an Oracle EF Schema @ runtime. The MethodInfo[] is just there as my exploration of 'Hey, what's available?' and I'm remapping the ToTable without issue. I need to remap the Maps as well, which is something like:

modelBuilder.Entity<Table1>()
            .HasMany(e => e.Table2)
            .WithMany(e => e.Table1)
            .Map(m => m.ToTable("TABLE_1", "SCHEMA_1").MapLeftKey("KEY_1").MapRightKey("KEY_2"));

I need to (at runtime) get the SCHEMA_1 from the m.ToTable and remap to SCHEMA_2 (again, dynamically).

So the question I'm trying to ask is: Does anyone have an example of trying to grab an Action() at runtime?

I'm specifically dealing with: Map(Action(Of EntityMappingConfiguration(Of TEntityType)))

Thanks!





Can I use reflection to dynamically bind methods to my JTextFields?

I have a page with several JTextFields. All of their variable names start with txt i.e. txtCarArea, txtRopeLength,....

I have an orderObject, that has several fields and setters / getters to use them.

The textfields get filled with the values from the fields of the orderObject like this:

// Around 50 fields get filled like this
txtCarArea.setText(orderObject.getCar_area());
....

The user then can change the values.

Now I could get the values of every textfield and put it into the orderObject after the user clicks on a button like "Apply changes", but this again would mean I have to write 50 setter-uses and fire all of them, even if the user only changed a value in one field:

@Override
public void actionPerformed(ActionEvent e) {
    // Again: Around 50 uses of the different setters
    orderObject.setCar_area(txtCarArea.getText());
    orderObject.setRope_length(txtRopeLength.getText());
    orderObject.setDoughID(txtDoughID.getText());
    (...)
}

This feels very bloated? I have to write and maintain those 50 calls.

Therefore I've read about reflection and tried to just use the setter-methods of the textfields that are changed and not all of them.

@Override
        public void actionPerformed(ActionEvent e) {
            orderObject.setCar_area(txtCarArea.getText());
            Method[] methods = orderObject.getClass().getDeclaredMethods();
            for (int i = 0; i < methods.length; i++) {
                String methodName = methods[i].getName();
                if (methodName.startsWith("set")) {
                    methodName = "txt" + methodName.substring(3);
                    String newMethodName = methodName.replace("_", "");
                    Method method = null;
                    try {
                        // "setCarArea" is hardcoded by me
                        method = orderObject.getClass().getMethod("setCarArea", String.class);
                    } catch (NoSuchMethodException e1) {
                        e1.printStackTrace();
                    } catch (SecurityException e1) {
                        e1.printStackTrace();
                    }
                    try {
                        // How to invoke dynamically for every textfield?
                        method.invoke(orderObject, "1070");
                    } catch (IllegalAccessException e1) {
                        e1.printStackTrace();
                    } catch (IllegalArgumentException e1) {
                        e1.printStackTrace();
                    } catch (InvocationTargetException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }

But since I dont know to find the pair of orderObject-setter + JTextField where the value is, I am stuck now.

So how can I dynamically get the correct setter-methods in the orderObject to input the values from the JTextFields?





Completely compromise restricted access to methods in plain java using reflection - why is that possible?

I'm totally puzzled - I wrote a class in Java8 SE (less than 10 lines of code) which completely compromises restricted (private) methods using reflection. I find this is very dangerous and question the sense of reflection allowing this.

package reflection;

import java.lang.reflect.Method;
import java.util.Arrays;

public class Reflection {

    //  Throw 'Throwable' because this method must be totally transparent, doing exactly what the actually called method does:
    static public Object call(Object target, String methodName, Object... args) throws Throwable {

        // Get the arguments' classes:
        Class<?>[] argumentClasses =
                Arrays.asList(args)
                    .stream()
                    .map(object -> object.getClass())
                    .toArray(Class[]::new);

        Method method = target.getClass().getDeclaredMethod(methodName, argumentClasses);
        method.setAccessible(true);
        return method.invoke(target, args);
    }

}

You can run this tests, which calls private methods - both static and non-static - of another class, Action:

package reflection;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class ReflectionUnitTest {

    @Test
    public void testCall() throws Throwable {

        Action target = new Action();

        assertEquals("Something static done!", Reflection.call(target, "doSomethingStatic"));
        assertEquals("Something static done with something else!", Reflection.call(target, "doSomethingStatic", "something else"));
        assertEquals("Something static done 3 times with something else!", Reflection.call(target, "doSomethingStatic", 3, "something else"));
        assertEquals("Something static done 5 times with something else!", Reflection.call(target, "doSomethingStatic", "something else", 5));

        assertEquals("Something done!", Reflection.call(target, "doSomething"));
        assertEquals("Something done with something else!", Reflection.call(target, "doSomething", "something else"));
        assertEquals("Something done 3 times with something else!", Reflection.call(target, "doSomething", 3, "something else"));
        assertEquals("Something done 5 times with something else!", Reflection.call(target, "doSomething", "something else", 5));
    }

}


package reflection;

public class Action {

    static private String doSomethingStatic(){

        return "Something static done!";
    }

    private String doSomethingStatic(String argument) {

        return "Something static done with " + argument + "!";
    }

    private String doSomethingStatic(Integer count, String argument) {

        return "Something static done " + count + " times with " + argument + "!";
    }

    private String doSomethingStatic(String argument, Integer count) {

        return "Something static done " + count + " times with " + argument + "!";
    }


    private String doSomething() {

        return "Something done!";
    }

    private String doSomething(String argument) {

        return "Something done with " + argument + "!";
    }

    private String doSomething(Integer count, String argument) {

        return "Something done " + count + " times with " + argument + "!";
    }

    private String doSomething(String argument, Integer count) {

        return "Something done " + count + " times with " + argument + "!";
    }

}

My issues:

  1. To share this knowledge with you
  2. To ask if anybody can explain why this is possible




How to parse DTO to Pojo objects

Well, I'm trying to parse objects and I'm having so much issues. My classes are like this:

-Entidad-

public class Entidad{

    private Long codEntidad;
    private Set<Comunicacion> comunicacion;


    /*------------ Getter and Setters --------------*/

}

-Comunicacion-

public class Comunicacion {

    private Entidad entidad;
    private Long codComunicacion;

    /*------------ Getter and Setters --------------*/

}

I need to parse to DTO objects:

-EntidadDTO-

public class EntidadDTO{

    private Long codEntidad;
    private Set<ComunicacionDTO> comunicacionDto;


    /*------------ Getter and Setters --------------*/

}

-ComunicacionDTO-

public class ComunicacionDTO {

    private EntidadDto entidadDto;
    private Long codComunicacion;

    /*------------ Getter and Setters --------------*/

}

I tried to use:

BeanUtils.copyProperties(entidad, entidadDto);

It seems that the parse is success but the property entidadDto.getComunicacionDto(); is a hashMap of Comunicacion (not ComunicacionDTO)

Should I try to make a custom parse with reflection?

Also I'd like to use this to parse more objects with a similar structure. Thanks!





Copy the state of controls and variables from one Form to another in c#

I have a windows form. If the user doesn't select a checkbox, a new form opens later when they press next, but if they do select it, the same form is used.
I want a clone of the current form to appear (with the same variable and control values) if they select the checkbox, so that they can change values later without deselecting the checkbox, and pressing next again, and typing in the other values manually.

Form duplicate = this; just references the same form and there is no such thing as new(this).
I couldn't try Form duplicate = new Form() = this as my form takes constructors from an earlier form

Anyone knows how to do this? Thanks in advance





mercredi 20 juillet 2016

Unable to find Interface in C# using reflection with Name.EndsWith

The name of interface is IService, but when I am trying to find the Interface in reflection in C#, it is not able to find because due to some reason the Interface name changes to Iservice'1

Please have a look to attached screenshot for Ildasm :

enter image description here

Actual Interface is like

 public interface IService<TOutput> 
        where TOutput : class, new()
    {
        Task<List<TOutput>> GetAllAsync(dynamic inputParameter);
    }

Code to find Interface: builder.RegisterAssemblyTypes(Assembly.Load("Services")) .Where(t => t.Name.EndsWith("Service"))

Here it fails to find Service, as IService is having some different name then defined one.

Any Idea why the name looks this way and how to resolve it ?





How to get Getter backing field from PropertyInfo?

I have a class as follows:

class Foo : PropertyChangedBase {
    private int _property;

    public int Property {
       get { return _property; }
       set { OnAssignPropertyChanged("Property", () => _property, value); }
}

PropertyChangedBase implements INotifyPropertyChanged with the following methods:

    protected void OnAssignmentPropertyChanged<T>(string propertyName, Expression<Func<T>> fieldExpression, T value)
    {
        var get = fieldExpression.Compile();
        if (get().Equals(value))
        {
            return;
        }

        //  invoke set property method
        SetProperty(fieldExpression, value);
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private void SetProperty<T>(Expression<Func<T>> fieldExpression, T value)
    {
        if (fieldExpression == null)
        {
            throw new ArgumentNullException(nameof(fieldExpression));
        }

        var memberExpression = fieldExpression.Body as MemberExpression;
        if (memberExpression == null)
        {
            throw new ArgumentException("fieldExpression");
        }

        var field = memberExpression.Member as FieldInfo;
        if (field == null)
        {
            throw new ArgumentException("fieldExpression");
        }

        field.SetValue(this, value);
    }

I would prefer to call:

OnAssignPropertyChanged(() => Property, value);

The only way this will work is if I can get the backing field for the property getter and then pass that to SetProperty. Is it possible to get the FieldInfo or target member from the property get method?