lundi 31 août 2015

How to get custom a list of methods C# with reflection

I have being using reflection to create a list of methods that the user would use in a dynamic generated menu (I'am in unity). I'am using:

MethodInfo[] methodInfos =  myObject.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

But not all public methods of the class should appear in this menu, so I was wondering, is there some flag which I could use to mark only the methods that I need?

And then use this "custom flag" to get those methods through reflection. Thanks :).





Why Nullable

While implementing a struct similar to Nullable<T> I've found that PropertyInfo.SetValue treats Nullable type differently then others. For Nullable property it can set value of underlying type

foo.GetType().GetProperty("NullableBool").SetValue(foo, true);

but for custom type it throws System.ArgumentException:Object of type 'SomeType' cannot be converted to type NullableCase.CopyOfNullable 1[SomeType] even if all conversion operators are overridden same way as in original Nullable<T>

Code to reproduce:

   using System;

namespace NullableCase
{
    /// <summary>
    /// Copy of Nullable from .Net source code 
    /// without unrelated methodts for brevity
    /// </summary>    
    public struct CopyOfNullable<T> where T : struct
    {
        private bool hasValue;
        internal T value;

        public CopyOfNullable(T value)
        {
            this.value = value;
            this.hasValue = true;
        }

        public bool HasValue
        {            
            get
            {
                return hasValue;
            }
        }

        public T Value
        {
            get
            {
                if (!hasValue)
                {
                    throw new InvalidOperationException();
                }
                return value;
            }
        }

        public static implicit operator CopyOfNullable<T>(T value)
        {
            return new CopyOfNullable<T>(value);
        }

        public static explicit operator T(CopyOfNullable<T> value)
        {
            return value.Value;
        }

    }


    class Foo
    {
        public Nullable<bool> NullableBool { get; set; }
        public CopyOfNullable<bool> CopyOfNullablBool { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Foo foo = new Foo();

            foo.GetType().GetProperty("NullableBool").SetValue(foo, true);
            foo.GetType().GetProperty("CopyOfNullablBool").SetValue(foo, true); //here we get ArgumentException 
        }
    }
}

Why does PropertyInfo.SetValue fails for CopyOfNullable type and passes for Nullable<T>?





Is it possible to cast to a type using type name in a string variable? [duplicate]

This question already has an answer here:

Is it possible to build a type name and recast an object to a specific type? The target types will be contained in the same assembly, and there will be hundreds. Example code:

var isPropertyInfo = objCollection as PropertyInfo;
if (isPropertyInfo != null)
{
    var propType = ((PropertyInfo)objCollection).PropertyType;
    var containerType = StripContainerType(propType.FullName);
    var itemType = StripItemType(propType.FullName);
    var fullTypeName = containerType + "<" + itemType + ">";
        // ex:  "System.Collections.Generic.ICollection<Customer>"
    var fullType = Type.GetType(itemType);
    dynamic coll;
    // now I want to do something *LIKE* (pseudocode-ish)
    // coll = objCollection as fullType;

Do not consider the last line as valid code. It's just where I'm stuck.





Getting Type + ConstructorInfo from ObjectCreationExpressionSyntax

I'm trying to get type and constructor info out of an ObjectCreationExpressionSyntax element.

I first need to assess that the created instance is an ArgumentException or a class that derives from it. Then, I need to get the ConstructorInfo (System.Reflection) that's being used.

public override void Initialize(AnalysisContext context)
{
    context.RegisterSyntaxNodeAction(c =>
    {
        var local = c.Node as ObjectCreationExpressionSyntax;

        if (local == null)
            return;

        ArgumentSyntax paramNameArgument;
        bool conditionsAreMet;

        // the code that's required to get both the Type and ConstructorInfo instances would go here

        if (conditionsAreMet)
        {
            c.ReportDiagnostic(Diagnostic.Create(Rule, paramNameArgument.GetLocation()));
        }
    }, SyntaxKind.ObjectCreationExpression);
}

The ObjectCreationExpressionSyntax has a Type property, which I'm pretty sure will be the starting point. However, I don't quite understand how am I supposed to extract anything from it.

Any guidance would be much appreciated.





Create an IEnumerable

I have a class that is composed of many collections like so:

public virtual ICollection<C> CStuff { get; set; }
public virtual ICollection<D> DStuff { get; set; }
public virtual ICollection<E> EStuff { get; set; }

Each of the types implement a common interface.

public class C : IStuff {}
public class D : IStuff {}
public class E : IStuff {}

I would like to create a collection of all the IStuff in my class, like so:

IEnumerable<IEnumerable<IStuff>> AllStuffCollections 
{
    get { /* how??? */ }
}

public IEnumerable<IStuff> AllStuff 
{ 
   get 
   { 
       foreach (IEnumerable<IStuff> stuffCollection in AllStuffCollections) 
       {
           foreach (IStuff stuff in stuffCollection) 
           {
               yield return stuff;
           }
       }
   }
}

Is there any way to accomplish this (reflection's OK) without adding each collection explicitly? As in, I don't want to do this:

IEnumerable<IEnumerable<IStuff>> AllStuffCollections 
{
    get 
    { 
        return new List<IEnumerable<IStuff>>() 
        { 
            CStuff.Cast<IStuff>, 
            DStuff.Cast<IStuff>,
            EStuff.Cast<IStuff>
        }
    }
}

Ultimately this class will be adding more collections of IStuff over time and I'm afraid I'll forget to include them in AllStuffCollections when it changes.

Additionally the collections themselves are lazy (EF-populated) so I don't want to do anything that would force an immediate "query all the things" to happen.





Ambiguous match found exception in BindingListView

I keep getting this exception while using Andrew Davey's BindingListView (http://ift.tt/1iyHHc3). I am using ServiceStack OrmLite . My objects looks like this:

public class Category
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [StringLength(50)]
    public string Name { get; set; }
}

and

public class Product
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [References(typeof(Category))]
    public int CategoryId { get; set; }
    public int ProductTypeId { get; set; }
    [StringLength(50)]
    public string Name { get; set; }
}

I have no idea how to pass this exception and I search everywhere for two days now. Any help would be appreciated. Thanks!





Is reflection execute the method in sequence order?

I have a class file, and I just want to get the list of methods name in that class and print it o/p console.

Just assume that I have following methods in Test1 class

public class Test1{

public static void test1()
{
//some code
}

public static void test2()
{
//some code
}

public static void test3()
{
//some code here.
}
}

I just need to call all the above methods from another class in the specific order.

Like test1() first, and second test2() and followed by test3();

What I did like I just created

 Method[] methodarray=Test1.getMethods();
    if(methodarray.getName().startWith("test"))
    {
    sysout(methodarray.getName())
    }

The above code print the method in specific order first time but not always. some times it prints 3rd method first and 1method seconds, and finally 2 method.

Can anybody tell me the reason?, and how to resolve this?.

-Sasi





C# - How to get the name of an interface Property/Func/Action, in a strongly type way?

Problem description

Assuming you have an interface / class, and wish to get a Property/Func/Action name, how and what is the best practice to do so?

e.g. given:

public interface IConvertible
{    
    // ...
    bool ToBoolean(IFormatProvider provider);
    // ...
}

How to get 'ToBoolean' name strongly timed fashion?





Get value from a ConstantExpression

I'm looking to get a value from an

Expression<Func<Someobject, bool>> selector = x => x.SomeId == "SOMEGUID-GUID-GUID-GUID-SOMEGUIDGUID";

For logging purposes I need to be able to fish out that guid.

I tried the following code, which I feel is somewhat close to what I'm looking for, but not quite.

BinaryExpression binaryExpression = (BinaryExpression)selector.Body;
MemberExpression memberExpression = (MemberExpression)((UnaryExpression)binaryExpression.Right).Operand;
ConstantExpression constantExpression = (ConstantExpression)memberExpression.Expression;

Now, ConstantExpression exposes a member 'Value', which does contain what I'm looking for, but I'm a bit puzzled how to actually extract this.

And no:

var val = (Guid)constantExpression.Value; 

Does not work :)





Dynamic Linq on method called with generic type via reflection

I have a Query Extender, which has a CustomExpression that I want to use to do some filtering on my datasource.

This is in a DynamicData website so I don't know the object type(current entity) at compile time. Say I knew the object type at compile time, then I could do something like this:

protected void GameFiltering(object sender, CustomExpressionEventArgs e)
{
        e.Query = e.Query.Cast<Resource>().Where(x => x.GameId == GameId);
}

I can get the type I need from e.Query.ElementType. Now I just to send the ElementType as a generic parameter to the Cast method and then call the linq method Where.

I'm gonna assume that every Type is going to have a GameId property which I'll want to filter by.

MethodInfo method = e.Query.GetType().GetMethod("Cast").MakeGenericMethod(new Type[] { e.Query.ElementType });
var castedQuery = method.Invoke(e.Query, null);

This is how I call the cast method with reflection, but I don't know how I can call the linq method on the resulting object.





Implement Java Reflection

I have implemented a query in mongo. I need to put the groupobj and sortobj in the pipeline as well.Since there will be lot of queries with a little variations I am thinking of using JAVA Reflection.

I have gone through the tutorial for JAVA Reflection and understood the concepts but I am not sure how to fit it into my requirement.

Any help !!

switch (dataId) {

        case ApplicationConstants.TOP_QUERIES_:

            // table = db.getCollection("tq");
            table = db.getCollection(MongoConstants.TOP_QUERY);

                MatchQuery.topQuery(matchObj, timePeriod);

            pipeline.add(matchObj);

            // group on term & totalcount
            final BasicDBObject groupObj = new BasicDBObject();
            groupObj.put("$group", new BasicDBObject(
                    ApplicationConstants._ID_FIELD, "$term").append(
                    ApplicationConstants.TOTAL_COUNTS, new BasicDBObject(
                            "$sum", "$count")));
            pipeline.add(groupObj);

            DBObject sort = null;

            // sort operation by count and alphabetically by term(storing in
            // _id)
            BasicDBObject sortByCount = null;

            if (filterObj.isSortOrder()) {
                sortByCount = new BasicDBObject(
                        ApplicationConstants.TOTAL_COUNTS, 1);
            } else {
                sortByCount = new BasicDBObject(
                        ApplicationConstants.TOTAL_COUNTS, -1);

            }
            sort = new BasicDBObject("$sort", sortByCount.append(
                    ApplicationConstants._ID_FIELD, 1));
            pipeline.add(sort);

            break;





dimanche 30 août 2015

Assembly.GetReferencedAssemblies method and portable class library

I think am getting bold trying to understand why in portable class library, which targets .net 4.5 and silverlight 5 and has support for MEF, some MEF and Reflection stuff is missing. For example: Assembly.GetReferencedAssemblies() doesn't exists in portable class library. DirectoryContainer from MEF doesn't exists. Problem is, i need it really bad. I have portable class library and ServiceLocator class in it.

public class ServiceLocator
{
    private Dictionary<Type, string> _defaultServices;

    [ImportMany(typeof(IService), AllowRecomposition = true, RequiredCreationPolicy = CreationPolicy.Shared)]
    private IEnumerable<Lazy<object, IService>> SharedServices { get; set; }

    [ImportMany(typeof(IService), AllowRecomposition = true, RequiredCreationPolicy = CreationPolicy.NonShared)]
    private IEnumerable<Lazy<object, IService>> NonSharedServices { get; set; }

    public ServiceLocator()
    {
        _defaultServices = new Dictionary<Type, string>();

        var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
        var cat = new AssemblyCatalog
        var container = new CompositionContainer(catalog);

        container.ComposeParts(this);

        foreach (var service in SharedServices)
        {
            if (service.Metadata.IsDefault)
            {
                SetDefaultService(service.Metadata.ServiceName, service.Metadata.ServiceInterface);
            }
        }
    }

Then, i have platform specific class library that references portable one, has class that implements IService interface from portable class library and exports it. Finally, i have WPF application that reference platform specific class library. The problem is, exported service is not in WPF application, but in referenced platform specific class library, so var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); can't import service. That is why i need DirectoryCatalog or Assembly.GetReferencedAssemblies(). Is there some workaround?





How to get the name of a method at runtime?

I'm using an event system that takes a string for the callback method name. I'd like to avoid hardcoding strings. Is there any way I can get the method names of given class in runtime?

Something similar to:

typeof(MyClass).Name;

but for methods would be perfect.

Edit:

I've been googling the problem and all results seem to be people looking to get the name of the current executing method. This isn't what I'm looking for - instead I'd like to get the name of other methods within the same class.





Java Dynamic Casting

I am using Apache POI to yield Excel reports, and since I would like each column to be compatible with its datatype (date, number, integer ...), I made up a static method to return an Object that can be "casted".

Since I am prone to reducing code as much as possible, I chose to do the following:

Object castableValue = Engine.formattingValue(value); cell.setCellValue((castableValue.getClass().cast(castableValue)));

However, this is not accepted at compile time by POI library, while I am sure it would work at run time.

I have to use if else for four datatypes (Double, Integer, Calendar, and String).

Any suggestions to achieve this dynamic solution ?





c# Cast int[] into MyType[] where MyType inherited from Enum?

I try to cast an int array int[] into Rights array Rights[], Rights is Enum by example... But it can be other type than rights but always inherited from Enum. I got the final type in a Type variable. I can create the Enum[] array but not the final Rights[] array for my methodInfo.Invoke(obj,param.ToArray()).

List<object> param = new List<object>();
ParameterInfo pi = ...
if (pi.ParameterType.IsArray && pi.ParameterType.GetElementType().IsEnum)
{
    List<Enum> enums = new List<Enum>();
    foreach (int i in GetTabInt())
    {
        enums.Add((Enum)Enum.ToObject(pi.ParameterType.GetElementType(), i));
    }
    param.Add(enums.ToArray()); // got Enum[] not Rights[]
}

Thank you for helping me!





samedi 29 août 2015

C#/Unity - Reflection - Object Does Not Match Target Type

I am trying to use Reflection (first time for me and I have looked through many of the other answers for this error and not found one that works for me)

Here is the Calling Method

void OnMouseDown(){
    CardName = GoldFate;

    Type classType = Type.GetType(CardName);
    Debug.Log ("Type: " + classType);

    MethodInfo theMethod = classType.GetMethod("Resolve"+CardName);
    Debug.Log ("MethodInfo: " + theMethod);

    theMethod.Invoke(this, null);
}

Here is the target:

public class GoldFate {
    public void ResolveGoldFate(){
        Debug.Log ("We got to Gold Fate");
    }
}

The output this generates is:

Type: GoldFate

MethodInfo: Void ResolveGoldFate()

TargetException: Object does not match target type. System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:236) System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Reflection/MethodBase.cs:115) FateCardManager.OnMouseDown () (at Assets/Scripts/Card Manipulation/FateCards/FateCardManager.cs:53) UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32, Int32)

I do not get to the Debug Message obviously

Thanks in advance





How to get the concrete type of base generic

Assuming I have a class A:

class A : B<C>, IA
{

}

And I also have a method like this:

Type GetConcreteB<T>() where T : IA
{
//some code here...
}

In this method I would like to check if T inherits from any B (currently I wrap B into an interface IB which does the thing) and if it does, return the concrete type of C.

So, basically I want to return the concrete type of the base generic class only using the subclass type. Is there a way to achieve this?





Can we use Function which takes dynamic values for optional interface for java8

I am new to java 8. Trying to pass Few inputs dynamically to get the values? Please let me know better suggestion

I have one object Request which will have input1(),input2() methods

void methodExecute(){ 
  Optional<Request> request = Optional.of(new Request()); 
 request.map(request::getInput1); //gives input1 value
  request.map(request::getInput2); //gives input2 value 
}

if we get getInput1,getInput2 comes as input(dynically) to this above method, can we dynamically get the values

below one is my approach. but not worked out

@FunctionalInterface
public interface Function_WithExceptions<T, V,R, E extends Exception> {
    R apply(T t,V v) throws E;
}

public class LambdaUtil<Input1, Input2> {
    public static <Input1,Input2, R, E extends Exception> 
                            Function_WithExceptions<Input1,Input2, R,E> rethrowFunction(Function_WithExceptions<Input1,Input2, R, E> function) throws E  {
        return (t,v) -> {
            try {
                return function.apply(t,v);
            } catch (Exception exception) {
                throwActualException(exception);
                return null;
            }
        };
    }
    @SuppressWarnings("unchecked")
    private static <E extends Exception> void throwActualException(Exception exception) throws E {
        throw (E) exception;
    }
}

public Function_WithExceptions getFunction(){
        Function_WithExceptions<GathererRequest, String,Object,Exception> requestObjParamFun = (reqObj,req)->MethodUtils.invokeExactMethod(reqObj, req);
        return requestObjParamFun;
}





PropertyInfo for a nested object

I have a string value: "object2.object3.object4"

This belongs to a type T. This is known.

How can I create a PropertyInfo object for the last property "object4" dynamically?

Thanks





vendredi 28 août 2015

Iterate through collection attribute of object with reflection

I'm trying to implement this solution in my code regarding cascading save in spring data mongodb. It works for normal class like this.

public class Test{

    @Id
    private String id;

    @DBRef
    @CascadeSave
    private Contact contact;
}

But I have something like this.

public class Test{

    @Id
    private String id;

    @DBRef
    @CascadeSave
    private Set<Contact> contacts = new HashSet<>();
}

I want to change the code in the listener which is in the link I have given to work with collections. I have tried several things and with no success. Apart from that, if there is another way accomplish this task, it would be appreciated, even though it is a separate question.

My listener code given below, which is not much difference to the example link.

public class CascadingMongoEventListener extends AbstractMongoEventListener {

private static final Logger logger = LoggerFactory.getLogger(CascadingMongoEventListener.class);

@Autowired
private MongoOperations mongoOperations;

@Override
public void onBeforeConvert(final Object source) {
     ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            try {
                if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) {
                    final Object fieldValue = field.get(source);
                    if (fieldValue != null) {

                        if (Collection.class.isAssignableFrom(field.getType())) {
                            @SuppressWarnings("unchecked")
                            Collection models = (Collection) fieldValue;
                            for (Object model : models) {
                               mongoOperations.save(model);
                            }
                        } else {
                            mongoOperations.save(fieldValue);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
    });
}

private static class DbRefFieldCallback implements ReflectionUtils.FieldCallback {
    private boolean idFound;

    public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
        ReflectionUtils.makeAccessible(field);
        if (field.isAnnotationPresent(Id.class)) {
            idFound = true;
        }
    }

    public boolean isIdFound() {
        return idFound;
    }
}
}





Using a map to fill a case class

Generic problem: I have a JSON-representation of a datastructure (which will be represented as a Map[String, Any] from now on) and a (case) class with some (!) of the key-value pairs as fields, but not all of them. I want to fill them in, with default values where the map has no pair (e.g. with constructor based default values for simplicity).

This would allow something like:

case clase User(id : Int, name : String, vegan : Boolean = false)
val map = Map("id" -> 42, "name" -> "tom")
val user = map.as[User] //User {42, "tom", false}

Coding it manually would be easy, but takes time and makes the code larger/harder to maintain/inspect (especially for >20 fields per class).

I feel like this needs to be possible by reflection, and more specifically at compile-time, without any performance detriment or problem with bytecode representation.

I know there are many questions (and answers) related to mapping maps to and from case classes, but most use deprecated apis, and the state of the art probably has progressed as well.





How can I get at runtime the type of a wildcard upper bound?

Suppose I am keeping a registry of subclasses of a certain class, T:

public class ClassRegistry<T> { Set<Class<? extends T>> klasses; ... public void register(Class<? extends T> klass) { klasses.add(klass); }

You register yourself with a call like registry.register(this.getClass()). I would like to make this simpler with a method on ClassRegistry<T> where you just pass yourself, this, e.g., registry.register(this):

public void register(Object obj) { Class<?> klass = obj.getClass(); this.register(klass); }

Oops, this is wrong, because it calls itself (matching the overload with parameter type Object and not, of course, Class<? extends T>). So, instead:

public void register(Object obj) { Class<? extends T> klass = obj.getClass(); this.register(klass); }

And now of course that doesn't compile because the compiler doesn't know that your obj is actually of some type ? extends T. And it might not, at that, because the caller might be wrong.

So my question is: How do I test/validate that obj is a subclass of T which is a wildcard upper bound (so I can safely cast)? (I suspect - or maybe, hope - the answer involves Guava's TypeToken, which is why I added the Guava tag, but I'll take any answer, thanks!)





An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll?

Project link: http://ift.tt/1WWURGy

It seems like this error pops up all over the place, in fairly esoteric problems with esoteric solutions. I've seen a few different MSDN/SO posts but none of their solutions apply to my problem. The program I've written doesn't actually use any reflection, and the error doesn't actually occur in the code so I think it's a problem in the other half of my project, a library that my test project references (which also doesn't use and kind of reflection).

If you have anything I can try, pls help





Unspecified FailedOperationException in Microsoft.SqlServer.Management.Smo.Server

I'm working on some SQL Server administration scripts. Part of the script needs to add/remove SQL Logins. The following works, adding john_doe0 into the root Security.Logins:

Import-Module "sqlps" -DisableNameChecking
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null

$SQL_SERVER = New-Object 'Microsoft.SqlServer.Management.Smo.Server' $env:ComputerName
$username = "john_doe0"
$password = "ARandomPasswordString123"

$login = New-Object 'Microsoft.SqlServer.Management.Smo.Login' -ArgumentList $SQL_SERVER, $username
$login.LoginType = 'SqlLogin'

if (!($SQL_SERVER.logins).Contains($username)) {
    $login.Create($password);
}

But this doesn't, causing a drop failed error and an unspecified FailedOperationException.

Import-Module "sqlps" -DisableNameChecking
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null

$SQL_SERVER = New-Object 'Microsoft.SqlServer.Management.Smo.Server' $env:ComputerName
$username = "john_doe0"
$password = "ARandomPasswordString123"

$login = New-Object 'Microsoft.SqlServer.Management.Smo.Login' -ArgumentList $SQL_SERVER, $username
$login.LoginType = 'SqlLogin'

if (($SQL_SERVER.logins).Contains($username)) {
    $login.Drop();
}

Now, I checked the documentation up and down, including for example this page:

http://ift.tt/1PXd3em

I don't see anything about expected exceptions here.

Oh, and also, I'm using a fresh install of SQL Server 2014. The tables have nothing unusual or out of the ordinary about them.

I'm hoping someone knows what might cause the Drop() method from executing against a login that is known to exist.

EDIT

I'm able to delete the logins via the GUI with no problems, and the Powershell operation occurs while I'm logged in to the Server. My purpose is a customized bulk operation.





Want to use reflection still work as it is eventhough the class is renamed

I store a fully qualified class name in a file. Let say in a xml file: mypackage.myclass

Then, somehowe refactoring is needed to change the package name. The new name is mynewpackage.myclass.

How can I still read the existing files because I dont want to change those files? What is the work around or is there any OO pattern that can be used here?

Thanks.





Convert via reflection retrieved object to string (how to iterate over multiple class types?)

I have a getterMethod that returns an type which I retrieve using:

getterMethod.getReturnType()

I need to cast this return value to string. Depending on the type of the returned value, I either need to just use .toString() method on the object, sometimes I need to do more work like using a stringformat for dates etc..

I couldn't help myself but going this way:

Integer i = 1;
if(i.getClass().isInstance(getterMethod.getReturnType())){
    // integer to string
}

But I have lots of possible types, what would be a good and fast approach to resolve this?





Using Method.getReturnType() on overridden method

I have a class that needs to get the return type of a method, that has been overwritten by something else.

Say that I have a class like:

public class SuperDuperClass {
    public Object someMethod();
}

I then create a subclass:

public class DuperClass extends SuperDuperClass{
    public String someMethod();
}

I then get the someMethod() for DuperClass:

Method theMethod = DuperClass.class.getMethod("someMethod", new Class[]{});
Class theMethodReturnType = theMethod.getReturnType();

I would very much like the returnType to be String, as is defined in DuperClass. However, I receive Object, as defined in SuperDuperClass. It would seem reflection doesn't really care that the overriden method returns another type, so the supermethod type is returned.

Is there some what to get the return type of the subclass in this case?

I accept both voodoo, witchcraft and blood magic.





jeudi 27 août 2015

Generically wrapping API with explicit methods by type

I'm looking for a way to easily manage decisions based on type, or sets of types. (Example, if is string, double, etc do one thing, if is enum do something else, etc). I have a cross section of both importance AND maintainability being critical.

I am working with an API that forces the following convention.

double dblField;
if(!apiObj.IsNull("NameOfDOubleProperty"))
  dblefield = apiObj.GetDouble("NameOfDOubleProperty");

string stringField;
if(!apiObj.IsNull("NameOfStringProperty"))
   stringField = apiObj.GetDouble("NameOfStringProperty");

 //Repeat for each property

I LOATHE magic strings all over code. If I change something in the app I am reading this from, then I have to ocme add another one, or worse remember to rename every place.

Step1: On start up, get readonly static fields (generated by a single time reflection call). I have that.

Step 2: My question - if it is a string, double, or other common primitive, i have a generic apiobj.GetField that I can cast. However, in the case of some objects, i need special handling.

Thoughts or patterns?





illegalargumentexception argument type mismatch while invoking a method via reflection in RCP project

I am trying to invoke a method of class via reflection in RCP project,the Class is in a reference jar,while invoking the method illegalArgumentException argument type mismatch is thrown,the method which is invoked contains two arguments one of userdefined type and another of string,the class gets loaded and i also get the method but when i invoke the method with the arguments expection is thrown,but when i run this with a simple java application it works fine, is there any another way to do it in RCP ? I'm new to RCP.

loading jar :

       File file = new File("C:\\Users\\sample.jar"); 
       URL jarfile;
       jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");    
       this.loader = URLClassLoader.newInstance(new URL[] {jarfile});

     invoking method: 
        c = this.loader.loadClass("com.Sample");
          Method[] methods = c.getMethods();
          for (Method method2 : methods) {
            if((method2.getName().equals(methodName))){
              method2.setAccessible(true);
              Object[] param={new myType(),new String("Sample")};
              method2.invoke(c.newInstance(),param);
            } 





Getting property values of list of child objects

Let's say I have a Car class with some properties. One of the properties is an IEnumerable of another class, Passenger, with it's own properties.

public class Car
{
   public string Engine { get; set; }
   public int Wheels { get; set; }
   public IEnumerable<Passenger> Passengers { get; set }
}

I am able to get the values of the Engine and Wheels properties (and all others such properties). However, I can't figure out how to get the properties of all the Passenger objects. Here's what I'm doing to get the property values of a Car object:

Type type = car.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
   object carValue = property.GetValue(car, null); 
   Console.WriteLine(carValue.ToString());
}

This obviously doesn't give me the Passenger properties, but outputs something like this instead:

System.Collections.GenericList'1[Passenger]

How do I grab all the property values of every Passenger in the car.Passengers list?





How to get all Groovy variables with the last values using reflection

I would like in my groovy script to dump all variables and display all values.

I would like to do it dynamically because I would like to surround all my huge groovies by a try/catch. In catch part I want to dump all variables state with the stacktrace. The code should be generic to all groovies.

The problem is that this.getBinding().getVariables() doesn't return the correct variable state.

I've made a small script to illustrate the situation:

def test1 = 1;
test1 = 2;

int test2 = 1;
test2 = 2;

test3 = 1;
test3 = 2;

def errLog=new File("c:/temp/groovy_debug.txt");   
errLog.append("--------------------------------------------------------" + "\n");
errLog.append("  Context ["+getBinding().getVariables()+" ] \n");
errLog.append("--------" + "\n") ;

after the execution I get a very strange result

--------------------------------------------------------
  Context [[[creationStackTrace= <not available>], test1:null, errLog:null, test2:null, test3:2] ] 
--------

it means that the declared variables are always reported as null or as first assignment, but for not typed variables it get the last value. I would like to get the last situation for all variables (value=2).

Is it possible to get them?





mercredi 26 août 2015

Methods in reflected DLLs unable to be called. How can I get a better error message?

I'm trying to write a PowerShell script that will call a series of static methods in a static class (MyClass) contained within certain DLL (MyNamespace.MyLibrary.dll) through reflection. However, even calling the simplest of methods (MyNamespace.MyLibrary.MyClass.CallMe()) inside that library fails with the following error message:

Exception calling "CallMe" with "0" argument(s): "The type initializer for 'MyNamespace.MyLibrary.MyClass' threw an exception."
At C:\temp\powershellTest.ps1:41 char:1
+ $output = [MyNamespace.MyLibrary.MyClass...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : TypeInitializationException

The first odd thing is that I'm getting a type initialization (constructor?) error when trying to call a static method in a static class.

The PowerShell code making the call:

[reflection.assembly]::LoadFile($dllLocation + 'MyNamespace.MyLibrary.dll')
$output = [MyNamespace.MyLibrary.MyClass]::CallMe()
Write-Host $output

The relevant C# code:

namespace MyNamespace.MyLibrary
{
    public static class MyClass
    {
        public static string CallMe() // the CallMe() method was added just to try to debug this
        {
            return "I was called";
        }
    }
}

Now, this particular library is much larger and has many dependencies, all used within other methods in MyClass. I made another DLL that is literally as simple as can be (no external dependencies) to test my powershell reflection, and it succeeds in calling a static class' method (also static, obviously). This tells me that my powershell is correct, so I looked up why I might be getting this issue. This comment says that it may not be automatically loading all of MyNamespace.MyLibrary's references.

I tried two things to remedy that:

  1. I copied all non-GACed DLLs referenced by MyLibrary into the same folder so they'd be side-by-side with MyLibrary.dll

  2. When that didn't work, I also added explicit [reflection.assembly]::LoadFile(path\otherAssembly.dll) lines after the one for MyNamespace.MyLibrary.dll to make sure powershell could load them. This also didn't work.

Here's my main question: How can I get a more specific error message about which dependency isn't being found and possibly where it's looking? I was shocked when Attempted Fix #1 wasn't enough, and I'm not sure what else I can do.

I hope that made sense; feel free to ask any necessary clarifying questions. Thanks!





How to create delegate of Func when b has parameters

I am trying to call a method that takes in a function, but using relection. I've gotten it to work when the method is parameterless but I can't figure out how to invoke it when there are arguments. This is a contrived simplified example, but this boils down the problem. I will not know the arguments to Add until runtime.

Any pointers? Do I have to use expression trees? Is there an easier way to do this?

public void Main()
{
    //works
    CallFunction(typeof (Processor), "Count");
    //I don't understand what I need to modify to make add work
    CallFunction(typeof (Processor), "Add");
}

public void CallFunction(Type type, string methodToCall)
{
    var targetMethod = type.GetMethod(methodToCall);
    var constructedType = typeof (MethodCaller<>).MakeGenericType(type);
    dynamic target = Activator.CreateInstance(constructedType);
    var method = constructedType.GetMethod("Do").MakeGenericMethod(targetMethod.ReturnType);
    var func =  typeof (Func<,>).MakeGenericType(type, targetMethod.ReturnType);
    var toCall = Delegate.CreateDelegate(func, targetMethod);
    method.Invoke(target, new object[] { toCall });
}

public class Processor
{
    public int Count()
    {
        return 1;
    }
    public int Add(int toAdd)
    {
        return 1 + toAdd;
    }
}

public class MethodCaller<TParm> where TParm : new()
{
    public TResult Do<TResult>(Func<TParm, TResult> func)
    {
        return func(new TParm());
    }
}





Accessing inner hidden abstract class to get status updates

I want to invoke a private method which takes abstract class parameter and that abstract class is hidden (I can not access it directly). I need to get the updates whenever methods of abstract class are invoked by some other class.

Class I am refereeing to is:

public class A{

  private void method(AbstractClassA object){ ... }

 // please note below class is hidden. I can not do A.AbstractClassA . I have to access it using reflection unless there is any other way

  public abstract class AbstractClassA {

  //I am interested in getting this int whenever someone else calls the progressUpdate

       public void progressUpdate(int update);
   }
}

I am trying to access like this:

public class myClass{

    Class<?> abstractClass =  Class.forName("<package>.A$AbstractClassA");
    A a = new A();
    Method someMethod = a.getDeclaredMethod("method", (Class[])null);
    someMethod.setAccessible(true);
    someMethod.invoke(a, <something which I don't know>); //how to pass paramerts here so that I get all callbacks whenever progressUpdate is called by someone else and "update" parameter is changed.


}





How to write the main method result, called by Reflection, to a string.

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.io.*;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import marea.GetPackage;

public class Execution extends ClassLoader {

    @SuppressWarnings("resource")
    public void invokeClassMethod(File source, String classBinName, String methodName){


    try{

        System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.8.0_51\\jre");   

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int compResult = compiler.run(null, null, null, source.getPath());

        if (compResult != 0) {
            System.out.println("compil!");
        }
        else{ 

                try {

                    File file = new File("C:\\Users\\abc\\");

                    URL url = file.toURI().toURL(); 

                    URL[] urls = new URL[] { url }; 

                    ClassLoader loader = new URLClassLoader(urls);

                    Class <?> thisClass = loader.loadClass(classBinName);

                    Constructor<?> constructor = thisClass.getConstructor();

                    Object Obj = constructor.newInstance();         

                    Method myMethod = thisClass.getDeclaredMethod("main",new Class[] { String[].class });

                    myMethod.setAccessible(true);

                    myMethod.invoke(Obj,new Object[] { new String [0] });

                }
                catch (Exception e){
                    e.printStackTrace();
                }
        }
    }
    catch (Exception e){
        e.printStackTrace();
    }

}

public static void main (String args[]){
    Execution javaClassLoader = new Execution();

    File source = new File("C:\\Users\\abc\\HelloWorld.java"); 

    String pak = GetPackage.getPackage(source);
    String clas = GetPackage.getClass(source);
    String classNameToBeLoaded;

    if (pak != "")  classNameToBeLoaded = pak + "." + clas;
    else    classNameToBeLoaded = clas;

    javaClassLoader.invokeClassMethod(source,classNameToBeLoaded,"main");
   }
}

If I run this I will get "Hello, World" message on the console. The message is the result of the main method of the HelloWorld.class file . Because the main method does not have a returned type and it is called by reflection, I do not know how to get the result and put it in a String variable.

Can you give me some ideas, please? (with code)





Best way to populate datatable into datamodel with huge number of properties in C#

I have a mainframe database from which I am exporting 5 lakh records using ODBC . Now I have to populate the datatable into data model(object). The data model or class has more than 150 properties which needs to be populated from datatable. I am using reflection to do so inside every iteration of each datarow. I could have use list or reader properties to populate from datatable but there I have to define 150 members. To avoid and make it more generic I choosed to use reflection.

 DataModel model = null;
//DataModel  is a class containing various properties 
//i.e public class DataModel
//{
//  public string Name {get;set;}
 // public string Role {get;set;}
//etc....150 properties
//}

    dt = new DataTable();
    using(OdbcDataReader reader = cmd.ExecuteReader())
    {
    DatatTable dtSchema = reader.GetSchemaTable();
    List<DataColumn> listCols = new List<DataColumn>();
    if(dtSchema != null)
    {
     foreach(DataRow drow in dtSchema.Rows)
    {
    string ColName = Convert.ToString(drow["ColumnName"]);
    DataColumn column = new DataColumn(columnName,(Type)(drow["DataType"]));
    listCols.Add(column);
    dt.Columns.Add(column);
    }
    PropertyInfo[] properties = typeof(DataModel).GetProperties();

    while(reader.Read())
    {
    DataRow dataRow = dt.NewRow();
    for(int i = 0; i < listCols.COunt; i++)
    {

    dataRow[((DataCOlumn)listCols[i])]
    }
    dt.Rows.Add(dataRow);

    model = new DataModel();
    foreach(PropertyInfo property in properties)
    {
      if(dt.Columns.Contains(property.Name))
        SetValue(model,property.name,dataRow[property,name]);

    }
    if(model != null) lst.Add(model);
    }

    }

I am getting exception by using this approach of reflection . Can the above be rectified and any different approach can be used ? I am using reflection to do so inside every iteration of each datarow. Please tell me is there any other good or more performance efficient method apart from reflection to do so. (Please note I have more than 150 properties that needs to be populated)





How to get the actual type of a generic function in Scala?

How can I get the actual type a generic function is called with?

The following example should print the type the given function f returns:

def find[A](f: Int => A): Unit = {
  print("type returned by f:" + ???)
}

If find is called with find(x => "abc") I want to get ""type returned by f: String". How can ??? be implemented in Scala 2.11?





How to invoke a GUI Class from external apk in android

I have loaded a external apk through DexClassLoader. in a method will be invoked has a GUI load from .xml layout. But i can not view this GUI (from external apk) through invoke method !!

In conclusion, I want to load a GUI from an external APK file through invoke method. Please help me !! p/s: sorry about my english!

final File _optimizedDexOutputPath = getDir("outdex", Context.MODE_PRIVATE);
    String _className;
    String _methodToInvoke;
    String _apkfilePath;


    HashMap<String, String> hmData;

    //Prepare
    hmData = preWorkflow();
    _className = hmData.get("className");
    _apkfilePath = hmData.get("apkfilePath");
    _methodToInvoke = hmData.get("methodToInvoke");


    DexClassLoader dLoader = new DexClassLoader(_apkfilePath,
            _optimizedDexOutputPath.getAbsolutePath(),
            null, ClassLoader.getSystemClassLoader().getParent());
    try {
        Class<?> loadedClass = dLoader.loadClass(_className);
        Object obj = (Object) loadedClass.newInstance();

        Method m = loadedClass.getDeclaredMethod(_methodToInvoke);
        m.invoke(obj);

    } catch (IllegalAccessException e) {
        e.getCause().printStackTrace();
    } catch (InvocationTargetException e) {
        e.getCause().printStackTrace();
    }catch (NullPointerException e){
       e.getCause().printStackTrace();
    }  catch(Exception ex) {
        ex.printStackTrace();
    }





Java org.reflection - Create the proper ConfigurationBuilder

I'm trying to setup a ConfigurationBuilder for the library Reflections, which use the following configuration:

I'm using the library through a Maven dependency

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.10</version>
</dependency>

with the last available version, 0.9.10

Here is the 3 constraints which I need to apply to the scanner:

  • annotated with @Annotation1 or @Annotation2
  • declared in the package package1, package2 or package3
  • an extension of the class SuperClass.class

This is the code I managed to create

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

// Package filter
FilterBuilder scannerFilter = new FilterBuilder();
scannerFilter.includePackage("com.mypackage1");
scannerFilter.includePackage("com.mypackage2");
scannerFilter.includePackage("com.mypackage3");
configurationBuilder.filterInputsBy(scannerFilter);

// Search only extended class of SuperClass
configurationBuilder.setUrls(Arrays.asList(ClasspathHelper.forClass(SuperClass.class)));

Reflections reflections = new Reflections(configurationBuilder);

// Get all the classes with annotation @Annotation1 or @Annotation2
Set<Class<?>> annotation1Classes = reflections.getTypesAnnotatedWith(Annotation1.class);
Set<Class<?>> annotation2Classes = reflections.getTypesAnnotatedWith(Annotation2.class);

but it does not works. This line

Reflections reflections = new Reflections(configurationBuilder);

triggers the following error:

ago 26, 2015 1:22:22 PM com.google.appengine.tools.development.agent.impl.Transformer transform
GRAVE: Unable to instrument javassist.bytecode.annotation.ShortMemberValue. Security restrictions may not be entirely emulated.
java.lang.RuntimeException
    at com.google.appengine.repackaged.org.objectweb.asm.MethodVisitor.visitParameter(MethodVisitor.java:114)
    at com.google.appengine.repackaged.org.objectweb.asm.ClassReader.readMethod(ClassReader.java:959)
    at com.google.appengine.repackaged.org.objectweb.asm.ClassReader.accept(ClassReader.java:693)
    at com.google.appengine.repackaged.org.objectweb.asm.ClassReader.accept(ClassReader.java:506)
    at com.google.appengine.tools.development.agent.impl.Transformer.rewrite(Transformer.java:146)
    at com.google.appengine.tools.development.agent.impl.Transformer.transform(Transformer.java:113)
    at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
    at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:424)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:199)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at javassist.bytecode.AnnotationsAttribute.getAnnotations(AnnotationsAttribute.java:227)
    at org.reflections.adapters.JavassistAdapter.getAnnotationNames(JavassistAdapter.java:156)
    at org.reflections.adapters.JavassistAdapter.getClassAnnotationNames(JavassistAdapter.java:50)
    at org.reflections.adapters.JavassistAdapter.getClassAnnotationNames(JavassistAdapter.java:24)
    at org.reflections.scanners.TypeAnnotationsScanner.scan(TypeAnnotationsScanner.java:12)
    at org.reflections.scanners.AbstractScanner.scan(AbstractScanner.java:35)
    at org.reflections.Reflections.scan(Reflections.java:250)
    at org.reflections.Reflections.scan(Reflections.java:204)
    at org.reflections.Reflections.<init>(Reflections.java:129)
    at it.noovle.ape.core.persistence.objectify.ObjectifyManager.getClassesToRegister(ObjectifyManager.java:107)
    at it.noovle.ape.core.listener.ObjectifyServantLoader.contextInitialized(ObjectifyServantLoader.java:51)
    at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:548)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:136)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
    at org.mortbay.jetty.Server.doStart(Server.java:224)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:266)
    at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:288)
    at com.google.appengine.tools.development.AutomaticInstanceHolder.startUp(AutomaticInstanceHolder.java:26)
    at com.google.appengine.tools.development.AbstractModule.startup(AbstractModule.java:87)
    at com.google.appengine.tools.development.Modules.startup(Modules.java:105)
    at com.google.appengine.tools.development.DevAppServerImpl.doStart(DevAppServerImpl.java:258)
    at com.google.appengine.tools.development.DevAppServerImpl.access$000(DevAppServerImpl.java:47)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:213)
    at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:211)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:211)
    at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:270)
    at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
    at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:218)
    at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:209)

I should mention that I'm working on a Google App Engine project

I also tried starting from the sample provided in the home page

//scan urls that contain 'my.package', include inputs starting with 'my.package', use the default scanners
Reflections reflections = new Reflections("my.package");

//or using ConfigurationBuilder
new Reflections(new ConfigurationBuilder()
     .setUrls(ClasspathHelper.forPackage("my.project.prefix"))
     .setScanners(new SubTypesScanner(), 
                  new TypeAnnotationsScanner().filterResultsBy(optionalFilter), ...),
     .filterInputsBy(new FilterBuilder().includePackage("my.project.prefix"))
     ...);

but I'm unable to create a working code.





How to load all compiled class from a folder?

I have a folder operators .In this folder I have compiled file(one interface operator AND 4 class that implement operator) .The purpose is load all the .class file from this folder and use in the main program . I use this statments :

    File operatorFile = new File("D:\\operators");
    URL operatorFilePath = operatorFile.toURL();          
    URL[] operatorFilePaths = new URL[]{operatorFilePath};
    ClassLoader operatorsLoader = new URLClassLoader(operatorFilePaths);

 //Plus,Minus,Multiply,Divide are classes that implement operator interface
   Class[] operatorClass = new Class[]{ operatorsLoader.loadClass("Plus"), operatorsLoader.loadClass("Minus"),operatorsLoader.loadClass("Multiply") , operatorsLoader.loadClass("Divide") };

Then I use this statment to call .class file methods :

Method methodsInOperator;
Object instance;
String operatorSign;

for(Class operatorCls : operatorClass)
{
   instance = operatorCls.newInstance();
    methodsInOperator = operatorCls.getMethod("getSign", null); 
    operatorSign = (String)methodsInOperator.invoke(instance, null);
                    if(operatorSign.equals(elementInExpression[2]))
                    {
    methodsInOperator = operatorCls.getMethod("calculate", new Class[] { double.class, double.class } ); 
                        output =(double)methodsInOperator.invoke(instance, firstNumber, secondNumber);  
                    }
                }

But below statment dose not work dynamically and if we put another .class file to operators folder program stop working .

Class[] operatorClass = new Class[]{ operatorsLoader.loadClass("Plus"), operatorsLoader.loadClass("Minus"),operatorsLoader.loadClass("Multiply") , operatorsLoader.loadClass("Divide") };

My purpose is to load all classes dynamically and check if they implement operator and according to getSing() method choose the best class .Can anyone help me?





How to cast object to method return type

I want to set args.ReturnValue to instance of an object created from TResponse<T> method called Create.

[Serializable]
public sealed class LogError : OnMethodBoundaryAspect
{
    public override void OnException(MethodExecutionArgs args)
    {
        // Logging part..

        MethodInfo methodInfo = (MethodInfo)args.Method;

        // I want to replace line below comment to get TResponse<T> object instead of dynamic if possible
        dynamic returnValue = Activator.CreateInstance(methodInfo.ReturnType);
        args.ReturnValue = returnValue.Create(CodeMessage.InternalError, MessageType.Error, args.Exception);

        args.FlowBehavior = FlowBehavior.Return;
    }
}

Method ReturnType will always be TResponse<T>, but I don't know how to create instance of TResponse<T> based on method return type. TResponse<T> implements method with this signature:

.Create(CodeMessage.InternalError, MessageType.Error, args.Exception);

Create method is static method that returns TResponse<T> object with parameters set.

Since I didn't know how to do what I want I used Activator to create instance of method return type but it throws RuntimeBinderException when I call Create method.





How can i access the inner object values of an object in mvel?

Object obj=account; here account object contains books as inner object. So how can i access those values in mvel.

I am new to MVEL. So can you please auggest me how to overcome the above issue.





mardi 25 août 2015

How i can access inner class variable value using reflection in java?

Suppose i have class like below with multiple inner classes :

public class Constants {

public class Class1 {

public static final String IODATA                         = "IOData";
public static final String HUB_INPUTS                     = "HubInputs";

}

public class Class2 {

public static final String CLASS_INPUTS           = "Class Inputs";
public static final String AUXILIARIES_ON_BUTTON  = "Auxiliaries On Button";

}

public class Class3 {

public static final String CLASS_INPUTS           = "Class Inputs";
public static final String AUXILIARIES_ON_BUTTON  = "Auxiliaries On Button";

}

}

I want to access all inner class variable then i can write code like below and i can get the variable name and value:

public static void getClassNameMap() throws Exception {

Constants cons = new Constants();
Constants.Class1 class1 = cons.new Class1();
for (Field fields : class1 .getClass().getFields()) 
{
  System.out.println(fields.get(projectObjectCons).toString() +"--"+fields.getName());
}

}

But some how i get array of String of all inner classes name like :

String []arr = {"Class1","Class2","Class3"};

how can i get all inner class variable and value using these String class name ??? Because i can not make class instance using its string name. Please help me out.





Abstract callback in reflection method of java

I have a class in jar of which I want to invoke a method. But that method has parameter of abstract class and that abstract class is inner method of class in jar. Here is code:

   public abstract class A{

        private invokeThisMethod(AbstractClassA object){
        }

        private abstract class AbstractClassA {
              public void update(int remaining){}
        }
   }



public class myClass{

     //using Reflection get object of class A
      objectOfClassAusingReflection.inovke("invokeThisMethod", params)
}

Problem here is how do I create concrete implementation of AbstractClassA to pass in invoke method and get update method callbacks ?





Java reflection and classpath in Android Studio

I am trying to use reflection in Java to access hidden classes in Android source code so I can end a call programmatically. The problem I am having is the method forName() generates a java.lang.ClassNotFoundException whatever I do. I tried many things including writing the name of the class as a String with the package name as a prefix and put that as argument of forName("TelePhonyManager.tm"), same error message. I understand this has to do with the classpath but no fix so far.Even when I tested with the current class I'm working with, and its package name I had the same error.

Class c = Class.forName(tm.getClass().getName());
        Method m = c.getDeclaredMethod("getITelephony");
        m.setAccessible(true);
        Object telephonyService = m.invoke(tm); // Get the internal ITelephony object
        c = Class.forName(telephonyService.getClass().getName()); // Get its class
        m = c.getDeclaredMethod("endCall"); // Get the "endCall()" method
        m.setAccessible(true); // Make it accessible
        m.invoke(telephonyService); // invoke endCall()





create array list of instances of annotated classes

I have a problem with creating an arraylist of instances. I got a Set<Class<?>> and then I check if they implement a specific interface. If they do I want to add an instance of this class to an arraylist of the specific interface.

This is my code:

ArrayList<MyInterface> list = new ArrayList<>();
for (Class clazz : annotatedClasses) {
    if(MyInterface.class.isAssignableFrom(clazz)) {
        Object instance = clazz.getConstructor().newInstance();
        list.add(object); //ERROR: Object != MyInterface
    }
}

How can I solve this?





How to pass method to another method using Scala reflection?

Working with scala reflection i dived into a trouble with methods that receive another methods as argument. Suppose i have package lib like this:

package lib

object A {
   def reg(f: String => String) = ???
}

object B {
   def f(String) : String = ""
}

And i have external storage that contains full names of objects A and B. For instance:

val aPath = "lib.A"
val fPath = "lib.B.f"

When i execute invoke(aPath, fPath) method it using reflection must run such code:

lib.A.reg(lib.B.f)

How can i achive this with scala reflection ?





Invoke method dynamically with default values as parameters [duplicate]

This question already has an answer here:

I am trying to dynamically invoke some methods in a class using Java Reflection. Those methods have different amounts of parameters with varying types. Now, I am looking for an easy way to invoke them dynamically:

  • Primitive type parameters should use default value of primitive type as parameter value
  • Non-primitive type parameters should use NULL as parameter value

Here is what I have tried so far:

final List<Object> parameters = new ArrayList<Object>();
for (final Class<?> parameterType : method.getParameterTypes()) {
    if (parameterType.isPrimitive()) {

        // FIXME: use default value of primitive type
        final Class<?> nonPrimitiveClass = ClassUtils.primitiveToWrapper(parameterType);
        parameters.add(nonPrimitiveClass.newInstance());
    } else {
        parameters.add(null);
    }
}

final Screen currentScreen = (Screen) method.invoke(screenFactory, parameters.toArray());

Unfortunately my attempt to get the default value did not work as newInstance is trying to call the default constructor which is not existant for java.lang.Integer for example.

  1. Is there an easy way to get the primitive type default value without any external libraries except Apache lang?

  2. Is there another way to invoke methods dynamically with default parameters than my attempt?

Thanks in advance.





mockito how to verify using methodname and reflection

I have a spy or a mock of an object and I wants to verify that a method has been call problem, I receive methodname at execution Time not compilation time

I would like to do something like SimpleObj mockObject= Mockito.mock(SimpleObj.class); Class myClass = SimpleObj.class; Method meth = myClass.getMethod("getGuid");

  Mockito.verify(meth.invoke(mockObject));

I have made a kind of workaround using

MockingDetails mockingDetails = Mockito.mockingDetails(mockObject);

Collection<Invocation> invocations = mockingDetails.getInvocations();

List<String> methodsCalled = new ArrayList<>();
for (Invocation anInvocation : invocations) {
  methodsCalled.add(anInvocation.getMethod().getName());
}
assertTrue(methodsCalled.contains("getGuid");

Problem it works until I use PowerMockito : for standard method it works but if the method is final, the method is not present in mockingDetails.getInvocations(); (but even if not present in mockingDetails.getInvocations(); the real verify(mock).getGuid(); works in a good way

So if you have any idea/advice it would be glad

Regards





Instance of GenericArrayType interface

class ReflectionClass{
   public static void anyMethod(Type type){
      if(type instanceof GenericArraytype){
         // some code
      }
   } 
}
class Client{
   public static void main(String[] args){
      anyMethod(...);
   }
}

I'm trying to receive a "true" value in if(type instanceof GenericArraytype) statement.

So, what I should put as an argument into invocation of anyMethod method inside Client class?

From the Oracle Documentation about GenericArrayType interface:

GenericArrayType represents an array type whose component type is either a parameterized type or a type variable.

But, I also know that I can't create arrays of parameterized types from here

Thus, how can I achieve this?





Collect information of members of a Class using Reflection

I'm trying to collect information about members of a class in Java using the standard reflection API. I've been successful for the most part except for members which are java collections and nested. Something like...

class Foo {
    int bar;
    List<List<List<String>>> baz; // problematic.
}

I'm collecting all this information into a Map via recursing over nested fields.

Recurse(Foo) -> Recurse(baz) -> Recurse(List<List<String>>) -> Recurse(List<String>)...

If there is already a library to help with some of this which I might have skipped, please mention it. Much appreciated :)





Recursive reflection through object

I have method that walks through a class and checks if 2 objects has the same values.

private bool LoopThroughObjects<T>(T ob1, T ob2)
{
    Type type = ob1.GetType();
    System.Reflection.PropertyInfo[] props = type.GetProperties();

    foreach (var prop in props)
    {
        object ent1value = prop.GetValue(ob1, new object[] { });
        object ent2value = prop.GetValue(ob2, new object[] { });

        //If object is in the same namespace it's a nested element
        if(IsSameNameSpace(type.Namespace, prop.PropertyType.Namespace))
        {
            _depth++;
            ValidateEntity_AttributesNotSame(ent1value, ent2value);
        }
        else
            ComparerOutput.Add(_conjunction + prop.Name, ent1value.Equals(ent2value));

        if (BreakOnUnequally)
            if (!ent1value.Equals(ent2value))
                return false;
    }
    return true;
}

A example of an object that I can send:

public class RefelctionTestEntity
{
    public int Id { get; set; }
    public String Firstname { get; set; }
    public String Lastname { get; set; }
    public int Age { get; set; }
    public RefelctionTestEntity Child { get; set;}
    public Vehicle.Bikes Bike { get; set; }
}

I walk recursively through the object so I will also check the Child en the Bike. My question is what's the best methode to check these inner objects? What I do at this moment is check the namespace of the object against the parent namespace of the inner object:

private bool IsSameNameSpace(String baseNamespace, String propertyNamespace)
{
    if (String.IsNullOrEmpty(baseNamespace) || String.IsNullOrEmpty(propertyNamespace))
        return true;

    if (String.IsNullOrEmpty(baseNamespace) || String.IsNullOrEmpty(propertyNamespace))
        return false;

    String[] part = propertyNamespace.Split('.');
    return part[0].Equals(baseNamespace);
}





Convert reflect.value to reflect.method

I have the fallowing:

func NewMethodDescriptor(typ interface{}) *MethodDescriptor {

    reflectedMethod := reflect.ValueOf(typ)
    methodType := reflectedMethod.Type
    paramCount := methodType.NumIn() - 1
    ...

But when I try:

NewMethodDescriptor(func(){})

I get this compile time error:

methodType.NumIn undefined (type func() reflect.Type has no field or method NumIn)





lundi 24 août 2015

C# Method Attributes

Is there a way to achieve this without injection? Topic is a UserControl. I am trying to check for Title and set it in Attribute.

public partial class Topic: TopicBase
{
[Topic(Title = "My Topic")]
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
}

When I look for the Attribute I get null in TopicBase.cs

protected override void OnInit(EventArgs e)
    {
        var topicAttr = Attribute.GetCustomAttribute(this.GetType(), typeof(TopicAttribute)); //topicAttr is null here.
        if (topicAttr != null)
        {
            SetTopic(((TopicAttribute)topicAttr).Title);
        }
    }





Define private property using Emit?

I'm not sure why it does not work as what I expect. I'm trying to define a dynamic private property (just for experiment) but somehow it's always found by Reflection like as it's public (no BindingFlags.NonPublic is required to find it). Here is the Emit code:

var prop = typeBuilder.DefineProperty("MyProperty", PropertyAttributes.HasDefault,
                                      typeof(string), null);
var backingField = typeBuilder.DefineField("_myProperty", typeof(string), FieldAttributes.Private);
var getter = typeBuilder.DefineMethod("get_MyProperty", MethodAttributes.Private, typeof(string), null);
var getterIL = getter.GetILGenerator();
getterIL.Emit(OpCodes.Ldarg_0);
getterIL.Emit(OpCodes.Ldfld, backingField);
getterIL.Emit(OpCodes.Ret);

var setter = typeBuilder.DefineMethod("set_MyProperty", MethodAttributes.Private, null, new []{typeof(string)});
var setterIL = setter.GetILGenerator();
setterIL.Emit(OpCodes.Ldarg_0);
setterIL.Emit(OpCodes.Ldarg_1);
setterIL.Emit(OpCodes.Stfld, backingField);
setterIL.Emit(OpCodes.Ret);

prop.SetGetMethod(getter);
prop.SetSetMethod(setter);

var t = typeBuilder.CreateType();

Now I expect the Reflection won't be able to find it without using the BindingFlags.NonPublic but it's still be found with this code:

var myProp = t.GetProperty("MyProperty");//this should not be able to 
                           //find the property, but it does.

In fact it's actually generated as public because if I try finding it as private, the result will be null:

//this will be null
var myProp = t.GetProperty("MyProperty", BindingFlags.Instance | BindingFlags.NonPublic);

So looks like it's very mysterious about how to define private property using Emit. I've even searched for that exact keywords but there are just a new result related (in title) but not actually involving the problem.

I hope you could give me some solution for this problem. Thank you.





Getting "java.lang.reflect.InvocationTargetException" when trying to register broadcast receiver of embedded apk

My app has an embedded APK, I need to register broadcast receiver of inner apk from main apk. Inner APK is not to be installed on the system, I must load it dynamically. So, I'm using reflection to call a method of inner apk which has code to register the receiver. This receiver of inner apk should invoke for related broadcast.

I'm getting error while trying to register receiver. Is it even possible for a receiver to be registered in this way, and be fully functional?
Exception and code is given below, please guide me if there is something wrong with the code.

Error related log is given below

08-24 08:31:26.915: D/MainApp(1957): invoke method
08-24 08:31:26.955: D/InnerApp(1957): Register receiver
08-24 08:31:26.955: W/System.err(1957): java.lang.reflect.InvocationTargetException
08-24 08:31:26.965: W/System.err(1957):     at java.lang.reflect.Method.invokeNative(Native Method)
08-24 08:31:26.965: W/System.err(1957):     at java.lang.reflect.Method.invoke(Method.java:515)
08-24 08:31:26.965: W/System.err(1957):     at com.example.ea_mainapp.MainApp.invokeService(MainApp.java:105)
08-24 08:31:26.965: W/System.err(1957):     at com.example.ea_mainapp.MainApp.onCreate(MainApp.java:40)
08-24 08:31:26.965: W/System.err(1957):     at android.app.Activity.performCreate(Activity.java:5231)
08-24 08:31:26.975: W/System.err(1957):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-24 08:31:26.975: W/System.err(1957):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-24 08:31:26.975: W/System.err(1957):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-24 08:31:26.975: W/System.err(1957):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-24 08:31:26.975: W/System.err(1957):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-24 08:31:26.975: W/System.err(1957):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-24 08:31:26.975: W/System.err(1957):     at android.os.Looper.loop(Looper.java:136)
08-24 08:31:26.975: W/System.err(1957):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-24 08:31:26.975: W/System.err(1957):     at java.lang.reflect.Method.invokeNative(Native Method)
08-24 08:31:26.975: W/System.err(1957):     at java.lang.reflect.Method.invoke(Method.java:515)
08-24 08:31:26.975: W/System.err(1957):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-24 08:31:26.975: W/System.err(1957):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-24 08:31:26.975: W/System.err(1957):     at dalvik.system.NativeStart.main(Native Method)
08-24 08:31:26.985: W/System.err(1957): Caused by: java.lang.NullPointerException
08-24 08:31:26.985: W/System.err(1957):     at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:467)
08-24 08:31:26.985: W/System.err(1957):     at com.example.ea_innerapp.InnerApp.register(InnerApp.java:50)
08-24 08:31:26.985: W/System.err(1957):     ... 18 more`

Code of Main app is given below

    // invoke method
    Log.d(TAG,"invoke method");

    final String apkFile =TARGET_BASE_PATH+"EA_innerApp.apk";
    String className = "com.example.ea_innerapp.InnerApp";
    String methodToInvoke = "register"; 

     final File optimizedDexOutputPath = getDir("outdex", 0);

     DexClassLoader dLoader = new DexClassLoader(apkFile,optimizedDexOutputPath.getAbsolutePath(),
                null,ClassLoader.getSystemClassLoader().getParent());

        try {
            Class<?> loadedClass = dLoader.loadClass(className);
            Object obj = (Object)loadedClass.newInstance();
            @SuppressWarnings("rawtypes")
            Class noparams[] = {};
            Method m = loadedClass.getMethod(methodToInvoke, noparams);
            Object oNoparams[] = {};
            m.invoke(obj, oNoparams);

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

Code of invoked method is

    Log.d(TAG, "Register receiver");
    IntentFilter filter=new IntentFilter(); 
    filter.addAction("com.example.ea_mainapp.i");
    registerReceiver(obj_InnerReceiver,filter); `





Setting the propery, when not knowing which one

Say I have this class with a few members, for example (this is a contrived example, I'd rather no have a discussion about the intricacies of the real-life design. I really just want to convey the general idea here.):

public class Address
{
    public Guid Id { get; set; }
    public Guid? HouseId { get; set; }
    public Guid? FlatId { get; set; }
    public Guid? SomeOtherBuildingTypeId { get; set; 
}

Now as it happens there exist 3 methods to create an Address:

public void CreateAddressForHouse();
public void CreateAddressForFlat();
public void CreateAddressForSomeOtherBuildingType();

Under the surface this group of methods does the exact same thing, bar setting a different Id property in the Address class. This is causing quite some code duplication in the real life application and I want to rewrite this to something more general.

In my mind I can pass the name of the required property and its value to a CreateAddress function, in something like a Func. But I'm seriously lacking in this respect, where to start? What .NET stuff can I use out of the box? Or what specific keywords should I look for?





dimanche 23 août 2015

Converting simple class to IL failed due to some invalid IL code?

I'm trying to convert this simple class to IL code:

public class IL {
  Dictionary<string, int> props = new Dictionary<string, int>() { {"1",1} };
}

In fact I used ILDasm to know the IL instructions before trying to use Emit to create the class dynamically. The result it shows is:

.class public auto ansi beforefieldinit IL
   extends [mscorlib]System.Object
{
 .field private class [mscorlib]System.Collections.Generic.Dictionary`2<string,int32> props
 .method public hidebysig specialname rtspecialname 
      instance void  .ctor() cil managed
 {
 // 
 .maxstack  4
 .locals init (class [mscorlib]System.Collections.Generic.Dictionary`2<string,int32> V_0)
 IL_0000:  ldarg.0
 IL_0001:  newobj     instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string,int32>::.ctor()
 IL_0006:  stloc.0
 IL_0007:  ldloc.0
 IL_0008:  ldstr      "1"
 IL_000d:  ldc.i4.1
 IL_000e:  callvirt   instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string,int32>::Add(!0,
                                                                                                              !1)
 IL_0013:  ldloc.0
 IL_0014:  stfld      class [mscorlib]System.Collections.Generic.Dictionary`2<string,int32> IL::props
 IL_0019:  ldarg.0
 IL_001a:  call       instance void [mscorlib]System.Object::.ctor()
 IL_001f:  ret
 } // end of method IL::.ctor

} // end of class IL

From that, I tried using Emit like this:

var aBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new System.Reflection.AssemblyName("test"), AssemblyBuilderAccess.Run);
var mBuilder = aBuilder.DefineDynamicModule("module");
var tBuilder = mBuilder.DefineType("IL");        
var field = tBuilder.DefineField("props", typeof(Dictionary<string, int>), System.Reflection.FieldAttributes.Private);
var con = tBuilder.DefineConstructor(System.Reflection.MethodAttributes.Public | 
                       System.Reflection.MethodAttributes.HideBySig | 
                       System.Reflection.MethodAttributes.SpecialName | 
                       System.Reflection.MethodAttributes.RTSpecialName, 
                       System.Reflection.CallingConventions.HasThis, Type.EmptyTypes);

var conIL = con.GetILGenerator();            
conIL.Emit(OpCodes.Ldarg_0);            
conIL.Emit(OpCodes.Newobj, typeof(Dictionary<string,int>).GetConstructor(Type.EmptyTypes));                        
conIL.Emit(OpCodes.Stloc_0);                
conIL.Emit(OpCodes.Ldloc_0);
conIL.Emit(OpCodes.Ldstr, "1");
conIL.Emit(OpCodes.Ldc_I4_1);
conIL.Emit(OpCodes.Callvirt, typeof(Dictionary<string, int>).GetMethod("Add"));
conIL.Emit(OpCodes.Ldloc_0);
conIL.Emit(OpCodes.Stfld, field);

conIL.Emit(OpCodes.Ldarg_0);
conIL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
conIL.Emit(OpCodes.Ret);

Now try using it:

var t =  tBuilder.CreateType();
var instance = Activator.CreateInstance(t);//exception has been thrown here 
               //saying "Common Language Runtime detected an invalid program."

So that means the IL code would be wrong at some point. But comparing it with what's actually generated by ILDasm, I don't see any difference (with my understanding). Could you help me point out what's wrong here? Thank you.





Invoking a method through reflection in C# that takes a delegate as an Input in C#

I have an Employee Class Defined in a namespace and the snippet goes something like this

    namespace DelegatesSampleApplication
    {
        delegate  bool IsPromotable (Employee employee);
        class Program
        {
            public static void Main(string[] args)
            {
                List<Employee> empList = new List<Employee>();
                empList.Add(new Employee() { EmployeeId = 1, EmployeeName = "A", Salary = 7500, Experience = 2 });
                empList.Add(new Employee() { EmployeeId = 2, EmployeeName = "B", Salary = 11500, Experience = 6 });
                empList.Add(new Employee() { EmployeeId = 3, EmployeeName = "C", Salary = 14500, Experience = 5 });
                empList.Add(new Employee() { EmployeeId = 4, EmployeeName = "D", Salary = 10500, Experience = 7 });

                IsPromotable isPromotableObj = new IsPromotable(EnableToPromote);

                Employee EmployeeObj = new Employee();
                EmployeeObj.PromoteEmployees(empList, isPromotableObj);
            }

            public static bool EnableToPromote(Employee employee)
            {
                if (employee.Experience >= 5 && employee.Salary >= 10000)
                {
                    return true;
                }
                else
                    return false;
            }
        }

        class Employee
        {
            public int EmployeeId { get; set; }
            public string EmployeeName { get; set; }
            public int Salary { get; set; }
            public int Experience { get; set; }

            public void PromoteEmployees(List<Employee> employeeList, IsPromotable isPromotableObj)
            {

                foreach (Employee employee in employeeList)
                {
                    if (isPromotableObj(employee)) 
                    {
                        Console.WriteLine(" {0} will be promoted in the next R.P. Cycle ", employee.EmployeeName);
                    }
                }
                Console.ReadKey();
            }
        }
    }

Now from a separate class in a separate namespace via reflection I want to get the Class Type and all other type objects related to it. Also I want to invoke the PromoteEmployee() method. How do I do that ?

namespace ReflectionSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***************Loading External assembly*************");
            Assembly assembly = Assembly.LoadFrom(@"C:\Users\Chiranjib\Documents\visual studio 2012\Projects\DelegatesSampleApplication\DelegatesSampleApplication\bin\Debug\DelegatesSampleApplication.exe");
            Type employeeType = assembly.GetType("DelegatesSampleApplication.Employee"); //Gets the System.Type object for the Employee Class from the just loaded assembly with all it's dependencies

            object employeeInstance = Activator.CreateInstance(employeeType);//Create an instance of the Employee Class Type
            Console.WriteLine("***************Loading External assembly properties*************");
            PropertyInfo[] propertyInfoColl =  employeeType.GetProperties();
            foreach(var item in propertyInfoColl)
            {
                Console.WriteLine("Loaded Type Property Name {0} and default value {1}", item.Name, item.GetValue(employeeInstance, null));
            }
            Console.WriteLine("***************Setting External assembly propeties for the first instance*************");
            PropertyInfo employeeId = (PropertyInfo)employeeType.GetProperty("EmployeeId");
            employeeId.SetValue(employeeInstance, 1);
            Console.WriteLine("Employee Id Property value now set to " + employeeId.GetValue(employeeInstance,null));
            PropertyInfo employeeName = (PropertyInfo)employeeType.GetProperty("EmployeeName");
            employeeName.SetValue(employeeInstance, "A");
            Console.WriteLine("Employee Name Property value now set to " + employeeName.GetValue(employeeInstance, null));
            PropertyInfo salary = (PropertyInfo)employeeType.GetProperty("Salary");
            salary.SetValue(employeeInstance, 40000);
            Console.WriteLine("Salary Property value now set to " + salary.GetValue(employeeInstance, null));
            PropertyInfo experience = (PropertyInfo)employeeType.GetProperty("Experience");           
            experience.SetValue(employeeInstance, 3);
            Console.WriteLine("Experience Property value now set to " + experience.GetValue(employeeInstance, null));
            Console.WriteLine("***************Setting External assembly propeties for the second instance*************");
            object employeeInstance2 = Activator.CreateInstance(employeeType);
            PropertyInfo employeeId2 = (PropertyInfo)employeeType.GetProperty("EmployeeId");
            employeeId2.SetValue(employeeInstance2, 2);
            Console.WriteLine("Employee Id Property value now set to " + employeeId2.GetValue(employeeInstance2, null));
            PropertyInfo employeeName2 = (PropertyInfo)employeeType.GetProperty("EmployeeName");
            employeeName2.SetValue(employeeInstance2, "B");
            Console.WriteLine("Employee Name Property value now set to " + employeeName2.GetValue(employeeInstance2, null));
            PropertyInfo salary2 = (PropertyInfo)employeeType.GetProperty("Salary");
            salary2.SetValue(employeeInstance2, 50000);
            Console.WriteLine("Salary Property value now set to " + salary2.GetValue(employeeInstance2, null));
            PropertyInfo experience2 = (PropertyInfo)employeeType.GetProperty("Experience");
            experience2.SetValue(employeeInstance2, 6);
            Console.WriteLine("Experience Property value now set to " + experience2.GetValue(employeeInstance2, null));
            Console.WriteLine("***************Creating an array list that will hold these employee instances***************");
            List<Object> employeeInstanceList = new List<object>();
            employeeInstanceList.Add(employeeInstance);
            employeeInstanceList.Add(employeeInstance2);
            Console.WriteLine("***************Invoking External assembly methods*************");
            var agrsDel = new Object[] {(employeeInstance) => return employeeInstance};

            dynamic value = employeeType.InvokeMember("PromoteEmployees", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, employeeInstance, new Object[] {employeeInstanceList,args})});
            Console.ReadKey();

        }
    }
}

But the errors I am getting are for agrsDel it cannot covert a lambda expression to an object and secondly object does not contain a definition for employeeId. What am I missing ? Please help me. Thanks a lot.





Getting value of int[] via reflection

Okay, so I'm trying to get the value of a int[] via reflection, and it's been going poorly. Here's my code:

What I'm trying to get value of

public int[] blah;

for(Field f : c.getDeclaredFields()) {
    f.setAccessible(true);
    if(f.getName().toLowerCase().contains("blah")) {
       Logger.write("Name: "+f.getName() +" Value:"+Array.get(f, 1));
    }
}

No matter what I do I keep getting "blah is not an array".





example of getOwnerType method

Could I ask about any example which uses getOwnerType() method where this method would return any Type object, but not a value "null" ?

This is a certain example of use getOwnerType() method which I found in Google:

public class Main {

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

      Type type = StringList.class.getGenericSuperclass();
      System.out.println(type); 
      ParameterizedType pt = (ParameterizedType) type;
      Type ownerType = pt.getOwnerType();
      System.out.println(ownerType);
   }
}

class StringList extends ArrayList<String> {

}

This is a result:

java.util.ArrayList<java.lang.String>
null

Everything is fine, because a value of pt object is a top-level type and null is returned.

And now, arguably I don't understand these words of documentation:

Returns a Type object representing the type that this type is a member of. For example, if this type is O< T >.I< S >, return a representation of O< T >.

After reading this, I tried do something like this:

public class Main {

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

      ... // a body of the main method is unchanged
   }
}

class StringList extends ClassA<String>.ClassB<String> {   // line No. 17

}

public class ClassA<T> {
   public class ClassB<T> {

   }
}

But, it produces only such error:

No enclosing instance of type r61<T> is accessible to invoke the super constructor. Must define a constructor and explicitly qualify its super constructor invocation with an instance of r61<T> (e.g. x.super() where x is an instance of r61<T>).

Maybe I tried to do something what doesn't make a sense, but I have no more ideas..





Set a readoly/InitOnly member field using Linq Expressions

Given a FieldInfo, it is possible to set a C# readonly / CLR InitOnly member field.

When and Why would I want to do this? its for a serializer, I create an empty instance of the object type, and I then populate all the fields from the data stream.

To the actual question:

Is there a way to achieve this using Linq Expressions also? the Expression.Assign results in a exception if you pass an expression pointing to the readonly/initonly field.

Or will I have to resort to IL emit to do this (faster than FieldInfo)





samedi 22 août 2015

Java - get propertie names referenced from method

So, I have this class:

public class Book {
private int id;
private String name;
private Something somebody;

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Book book = (Book) o;

    if (id != book.id && somebody.getId() != book.somebody.getId()) return false;

    return true;
}

@Override
public int hashCode() {
    return id;
}
}

I would like to get all properties used in this class in equals method - in this case, I would get "id" from Book (since name is not used in equals method), and I would also get "somebody.id" since this is also used in equals method as sub object.

I need this info, so I can serialize only this properties and then during de-serialization on another machine use only that to compare equals. Otherwise it would be too cumbersome to compare full objects for equals (if I have too many sub-properties).





java reflection: pass a value from the calling class but not as parameter

I have written a java class A with Method 'm' which I am loading dynamically in my program by reading A.class from the disk and using defineclass to recreate the class. Then I am invoking m in A.class from Main function of my program using m.invoke(instance of A). The Method does not take any parameters. Can I "somehow" read a variable defined in the Main function of my program from inside m once it has been invoked?





Set FieldInfo value using SetValue vs Linq Expressions

I want to set private fields using Linq Expressions. I have this code:

 //parameter "target", the object on which to set the field `field`
 ParameterExpression targetExp = Expression.Parameter(typeof(object), "target");

 //parameter "value" the value to be set in the `field` on "target"
 ParameterExpression valueExp = Expression.Parameter(typeof(object), "value");

 //cast the target from object to its correct type
 Expression castTartgetExp = Expression.Convert(targetExp, type);

 //cast the value to its correct type
 Expression castValueExp = Expression.Convert(valueExp, field.FieldType);

 //the field `field` on "target"
 MemberExpression fieldExp = Expression.Field(castTartgetExp, field);

 //assign the "value" to the `field` 
 BinaryExpression assignExp = Expression.Assign(fieldExp, castValueExp);

 //compile the whole thing
 var setter = Expression.Lambda<Action<object, object>> (assignExp, targetExp, valueExp).Compile();

```

This compiles a delegate that takes an object - the subject and another object - the value.

setter(someObject,someValue);

The variable field contains what field is supposed to be set.

This works great for reference types, but if the subject is a struct, this thing will pass the subject as a copy to the setter delegate and set the value there. (at least that is what I think is going on)

while

field.SetValue(someObject,someValue);

Works just fine, even for structs.

Is there anything I can do about this in order to set the field of the subject using the compiled expressons?

Thoughts?





Getting return of java.awt.Component via reflection

I have a Component inside of a client which I want to retrieve via reflection.

  Component getGameComponent()
  {
    if (blah != null) {
      return blah;
    }
    if (blah != null) {
      return blah;
    }
    return this;
  }

Now, how would I grab that component via reflection?





What may be an instance of ParameterizedType?

After reading a documentation of ParameterizedType interface I thought that an example of ParameterizedType's instance can be any parametrized type such as col in my code:

  public class a0 {

     public static void main(String[] args) {

        Collection<String> col = new ArrayList<String>();
        col.add("a");
        col.add("b");
        col.add("c");

        assert col instanceof ParameterizedType; // line No. 10
     }
  }

But I get this:

Exception in thread "main" java.lang.AssertionError
at a0.main(a0.java:10)

Thus, what may be an instance of ParameterizedType?

I'd like to know this because I am trying to understand one greater program in which there is such a fragment:

public static void printType(Type type) {
...
if (type instanceof ParameterizedType) {
... }
}

But I don't know when a condition in if statement is true..





Accessing a delegate via reflection declared outside of any class?

I am trying a demo for reflection. The assembly I want to reflect in this class goes something like this

namespace DelegatesSampleApplication
{
    delegate  bool IsPromotable (Employee employee); // Declaration Syntax is similar to that of a method's 
    class Program
    {
        public static void Main(string[] args)
        {
             //code goes here
        }
    }

    class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public int Salary { get; set; }
        public int Experience { get; set; }

        public void PromoteEmployees(List<Employee> employeeList, IsPromotable isPromotableObj)
        {

            /*foreach (Employee employee in employeeList)
            {
                if (employee.Experience >= 5 && employee.Salary >= 10000) //That's a hard-coded logic that you have developed as a Framework Developer which makes the class itself not reusable
                {
                    Console.WriteLine(" {0} will be promoted in the next R.P. Cycle ", employee.EmployeeName);
                }
            }
            Console.ReadKey();*/

            foreach (Employee employee in employeeList)
            {
                if (isPromotableObj(employee)) 
                {
                    Console.WriteLine(" {0} will be promoted in the next R.P. Cycle ", employee.EmployeeName);
                }
            }
            Console.ReadKey();
        }
    }
}

Now the problem I am facing is, I am trying to read from this assembly in my program and trying to invoke the delegate which takes in a class instance as a parameter.

How would I be able to access the delegate via reflection ? As I suppose

Type.GetNestedTypes() 

wont help my cause as it is not contained within any sort of classes. Please help me through. Thanks in advance.