mardi 31 mai 2016

No annotations present when reflecting a method using class.getDeclaredMethod

I'm writing some unit tests using reflection, and I'm having troubles to reflect a method preserving its annotations.

I declared this interface:

private interface Provider {
    void mock(@Email String email);
}

And I'm trying to reflect this method, as follows:

Class stringClass = String.class;
Method method = Provider.class.getDeclaredMethod("mock", String.class);
AnnotatedType annotatedType = method.getAnnotatedParameterTypes()[0];
Annotation annotation = annotatedType.getAnnotation(Annotation.class);

I would expect that annotation variable holds an instance of @Email annotation, but instead, it's a null reference.

So, how can I retrieve the annotations for an specific param when reflecting a method?

Thanks!





Visitor Pattern when there are numerous elements?

So I believe that I understand the fundamentals to implementing a visitor pattern, but what happens when there are too many concrete elements causing the visitor to be forced to include hundreds of methods to address each of these elements?

Would it be better to implement an alternative (ex. reflective visitor or dynamic dispatching visitor) or attempt to implement normal form visitor to that which already exists?

tl;dr: Visitor class is huge (>4000 lines) due to hundreds of concrete elements, what should I do?





Hibernate trying to set field value to object

Trying to use Hibernate from scratch for first time. I have entity class:

package centaurus.domain;

import javax.persistence.*;

@Entity
@Table(name="users")
public class Player {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="USER_ID")
    private int id;

    @Column(name="email")
    private String email;

    public Player(){};

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

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

    public int getId() {
        return id;
    }
}

DAOimpl: package centaurus.service;

import centaurus.domain.Player;

import restx.factory.Component;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

@Component
public class PlayerDAOimpl implements PlayerDAO{
    private static SessionFactory factory;

    public PlayerDAOimpl() {
        try{
            factory = new Configuration().
                    configure().addAnnotatedClass(Player.class).
                    buildSessionFactory();
            //
        }catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }

    }

    public Player savePlayer(Player player){
        Session session = factory.openSession();
        Transaction tx = null;
        Integer playerID = null;


        try{
            tx = session.beginTransaction();

            playerID = (Integer) session.save(player);
            tx.commit();

        }catch (HibernateException e) {
            if (tx!=null) tx.rollback();
            e.printStackTrace();
        }finally {
            session.close();
        }
        return player;
    }

    public Player getPlayer(Integer playerId){
        Session session = factory.openSession();
        try{
            Player player = (Player)session.get(Player.class, playerId);
            return player;
        }catch (HibernateException e) {

        }finally {
            session.close();
        }
        return null;
    }
}

to demo the error i made it add a player on startupscript.

and error:

 -- RESTX >> LOAD ON REQUEST << >> DEV MODE << >> AUTO COMPILE <<
 -- for admin console,
 --   VISIT http://ift.tt/1TIpafU
 --

2016-05-31 21:42:48,901 [main            ] [          ] INFO  restx.Apps - can't enable Apidocs doclet: make sure tools.jar is in your classpath
2016-05-31 21:42:49,978 [pool-1-thread-1 ] [          ] INFO  restx.classloader.CompilationManager - compilation finished: 12 sources compiled in 1.015 s
2016-05-31 21:42:50,061 [main            ] [          ] INFO  restx.Apps - can't enable Apidocs doclet: make sure tools.jar is in your classpath
2016-05-31 21:42:50,078 [main            ] [          ] INFO  restx.classloader.CompilationManager - watching for changes in [src/main/java, src/main/resources]; current location is /home/arthur/elorhia/api/.
2016-05-31 21:42:50,145 [main            ] [          ] INFO  org.hibernate.Version - HHH000412: Hibernate Core {5.1.0.Final}
2016-05-31 21:42:50,146 [main            ] [          ] INFO  org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
2016-05-31 21:42:50,147 [main            ] [          ] INFO  org.hibernate.cfg.Environment - HHH000021: Bytecode provider name : javassist
2016-05-31 21:42:50,802 [main            ] [          ] INFO  o.h.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2016-05-31 21:42:50,851 [main            ] [          ] WARN  org.hibernate.orm.connections - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
2016-05-31 21:42:50,856 [main            ] [          ] INFO  org.hibernate.orm.connections - HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/andromeda]
2016-05-31 21:42:50,857 [main            ] [          ] INFO  org.hibernate.orm.connections - HHH10001001: Connection properties: {user=api, password=****}
2016-05-31 21:42:50,858 [main            ] [          ] INFO  org.hibernate.orm.connections - HHH10001003: Autocommit mode: false
2016-05-31 21:42:50,860 [main            ] [          ] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 1 (min=1)
2016-05-31 21:42:51,090 [main            ] [          ] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
2016-05-31 21:42:51,321 [main            ] [          ] INFO  o.h.validator.internal.util.Version - HV000001: Hibernate Validator 5.0.1.Final
START SCRIPT!
org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.String centaurus.domain.Player.email] by reflection for persistent property [centaurus.domain.Player#email] : centaurus.domain.Player@507b79f7
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:43)
    at org.hibernate.property.access.spi.GetterFieldImpl.getForInsert(GetterFieldImpl.java:58)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValuesToInsert(AbstractEntityTuplizer.java:521)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.getPropertyValuesToInsert(PojoEntityTuplizer.java:228)
    at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValuesToInsert(AbstractEntityPersister.java:4701)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:254)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
    at centaurus.service.PlayerDAOimpl.savePlayer(PlayerDAOimpl.java:39)
    at centaurus.Dbmaintain.start(Dbmaintain.java:26)
    at restx.factory.Factory.start(Factory.java:846)
    at restx.RestxMainRouterFactory.build(RestxMainRouterFactory.java:450)
    at restx.RestxMainRouterFactory.newInstance(RestxMainRouterFactory.java:70)
    at restx.servlet.RestxMainRouterServlet.init(RestxMainRouterServlet.java:74)
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:519)
    at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:331)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:747)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:265)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:706)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:492)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
    at org.eclipse.jetty.server.Server.doStart(Server.java:277)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
    at restx.server.JettyWebServer.start(JettyWebServer.java:109)
    at restx.server.JettyWebServer.startAndAwait(JettyWebServer.java:114)
    at centaurus.AppServer.main(AppServer.java:30)
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field centaurus.domain.Player.email to centaurus.domain.Player
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:393)
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:39)
    ... 40 more
2016-05-31 21:42:51,673 [main            ] [          ] INFO  restx.monitor.MetricsConfiguration - registering Metrics JVM metrics
2016-05-31 21:44:41,646 [pool-2-thread-1 ] [          ] INFO  restx.classloader.CompilationManager - compilation finished: 1 sources compiled in 86.94 ms

it looks like its trying to set the email field to the player object. I cant work out why!, what have I done wrong?





How to go from MethodInfo[] to Action

I am mapping an xbox controller and want a way for the user to change what key does what in the program. I use a dictionary with the key as a ControllerEventArgs ( custom event args) and value is Action, which is the function that will be invoked when the button is pressed.

Everything is in place except one part: We are able to open a combo box with all they buttons (A Pressed, A Released, B, X, Y, etc) and using reflection and attributes I display all the possible methods (actions) the button can make. So the user goes ahead and chooses it - But now I have the method name in the MethodInfo[] and I need it as an Action to pass to/modify my dictionary. Any way to do this? I am new to reflection and attributes.





ReflectionToStringBuilder in given format [duplicate]

This question already has an answer here:

I have a POJO representing a record in DynmaoDB table:

class Request{
       String id,
       String name,
       Status statusName,
       }

where Status is

public enum Status{
  OPEN, REVIEW, APPROVED }

I want to get the String representing the fields in a fixed format, just like

Request_1 Name_1 OPEN

Request_2 empty_string APPROVED

empty_string represents an empty string which is used when the value of the field is not defined. What I am doing now is

String requestRecord = this.toString(request);

where the toString method is :

public String toString(Request request) {
        return new ReflectionToStringBuilder(request, new RecursiveToStringStyle()).toString();
      }

This gives me the output like this :

com.datamodel.Request@3bb5ceb[id=Request_1,name=,statusName=com.datatype.Status@2ffb3aec[statusName=Review,name=REVIEW,ordinal=1]]

Can anyone tell me how to get the string in the required format.?





c# assembly auto update on startup

I've an application that reference a dll. At startup of my application I want to check for a new version via web.

Anyone have any ideas about changing the older dll with the new one? without rewrite all method call with reflection?





how to add jar dynamically and put it at the beginning of the search path

I met a problem when using Java

let's say , when a java program start , it loads jarA , jarB , jarC (i can not control this step) , and in JarA , JarB , jarC they all have a class called "Demo" . and now in the code , i need to use "Demo" class from jarD

using ClassLoader , i can add jarD, but how can i make sure that , the "Demo" when i called ClassLoader.loadClass("Demo") give the class defined in jarD (not that class has the same name in jarA ,jarB , jarC)

thanks and looking forward to the answers !





lundi 30 mai 2016

How I can get class name that add in my class Path ? (Whitout use any library)

How I can get class name that add in my class Path ? for example : I have a package and in that package I have some classes. I need the name of that classes on run time.

package sample;

public class Sample{ }

-----------------------

package Test;

public class Test{

public static void main(String[] args){
     //?
}

}





Reflection help required c#

// is there any alternative for Assembly.Load(InjRes) method in this code? // foreach on the methods or some thing?

Assembly SampleAssembly = Assembly.Load(InjRes);

Type t = SampleAssembly.GetType("Resource.reflect");

MethodInfo BahNahNah = t.GetMethod("Run");

bool inj = (bool)BahNahNah.Invoke(null, new object[] { Assembly.GetExecutingAssembly().Location, "", Runner, false }); Console.WriteLine("Injected: {0}", inj);





Compare two objects using reflection

I have any classes :

public class Store
{
    public string id { get; set; }

    public List<Customer> Customer { get; set; }
}

public class Customer
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public List<Product> Product { get; set; }
}

public class Product
{
    public int ProductNumber { get; set; }

    public string ProductColor { get; set; }
}

And two instances :

Store Store1 = new Store
{
    id = "id1",
    Customer = new List<Customer>
    { 
        new Customer()
        {
            FirstName = "FirstName1",
            LastName = "LastName1",
            Product = new List<Product>
            {
                new Product()
                {
                    ProductColor = "ProductColor1",
                    ProductNumber = 1
                }
            }
        }
    }
};

Store Store2 = new Store
{
    id = "id2",
    Customer = new List<Customer>
    { 
        new Customer()
        {
            FirstName = "FirstName1",
            LastName = "LastName1",
            Product = new List<Product>
            {
                new Product()
                {
                    ProductColor = "ProductColor1",
                    ProductNumber = 2
                }
            }
        }
    }
};

I have a method who compare two objects with reflection :

public static bool AreEquals(object objectA, object objectB)
{
    if (objectA != null && objectB != null)
    {
        Type objectType = objectA.GetType();

        foreach (PropertyInfo propertyInfo in objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.CanRead))
        {
            object valueA = propertyInfo.GetValue(objectA, null);
            object valueB = propertyInfo.GetValue(objectB, null);

            if (typeof(IComparable).IsAssignableFrom(propertyInfo.PropertyType) ||
                propertyInfo.PropertyType.IsPrimitive ||
                propertyInfo.PropertyType.IsValueType)
            {
                if (!AreValuesEqual(valueA, valueB))
                    Console.WriteLine(string.Format("{0}.{1} not equal : {2} != {3} ", propertyInfo.ReflectedType.Name, propertyInfo.Name, valueA, valueB));
            }

            else if (typeof(IEnumerable).IsAssignableFrom(propertyInfo.PropertyType))
            {
                else if (valueA != null && valueB != null)
                {
                    IEnumerable<object> collectionItems1 = ((IEnumerable)valueA).Cast<object>();
                    IEnumerable<object> collectionItems2 = ((IEnumerable)valueB).Cast<object>();

                    for (int i = 0; i < collectionItems1.Count(); i++)
                    {
                        Console.WriteLine("{0}.{1}[{2}]", propertyInfo.ReflectedType.Name, propertyInfo.Name, i);

                        object collectionItem1 = collectionItems1.ElementAt(i);
                        object collectionItem2 = collectionItems2.ElementAt(i);
                        Type collectionItemType = collectionItem1.GetType();

                        if (typeof(IComparable).IsAssignableFrom(collectionItemType) ||
                            collectionItemType.IsPrimitive ||
                            collectionItemType.IsValueType)
                        {
                            if (!AreValuesEqual(collectionItem1, collectionItem2))
                                return false;
                        }
                        else if (!AreEquals(collectionItem1, collectionItem2))
                            return false;
                    }                   
                }
            }

            else if (propertyInfo.PropertyType.IsClass)
            {
                if (!AreEquals(propertyInfo.GetValue(objectA, null), propertyInfo.GetValue(objectB, null)))
                    return false;
            }
            else
            {
                Console.WriteLine("Cannot compare property '{0}.{1}'.", propertyInfo.ReflectedType.Name, propertyInfo.Name);
                return false;
            }
        }
        return true;
    }
    return false;
}

This method return :

enter image description here

But I want to get the full path of the property :

enter image description here

How to do this ? Or what is the best way to do this ?





Swift Mirror API - Which protocols an object conforms to

Is there a Swift Mirror API call that can tell me what protocols an object conforms to, ie:

protocol ProtocolA {}
protocol ProtocolB {}
protocol ProtocolC {}

class User : A, C {}

Then if I had the following code, it would print out A & C

let u = User()
let mirror = Mirror(reflecting: u)
let protocols = mirror.whichProtocols() // Made up code
print(protocols) //A & C





How to check if a field has an annotation when using reflection

I'm using reflection so I can check if some fields in another class have annotations.

DummyUser class:

package com.reflec.models;

public class DummyUser {

@NotNull
private String firstName;

private String lastName;

@NotNull
private String email;

public DummyUser() {

}

public DummyUser(String firstName, String lastName, String email) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
}

Main class:

public static void main(String[] args) {
    DummyUser user = new DummyUser();

    List<Field> list = seekFieldsWithAnnotations(user);         
    System.out.println("Size: " + list.size());
}

public static List<Field> seekFieldsWithAnnotations(Object o) {
    Class<?> clss = o.getClass();
    List<Field> fieldsWithAnnotations = new ArrayList<>();

    List<Field> allFields = new ArrayList<>(Arrays.asList(clss.getDeclaredFields()));
    for(final Field field : allFields ) {
        if(field.isAnnotationPresent((Class<? extends Annotation>) clss)) {
            Annotation annotInstance = field.getAnnotation((Class<? extends Annotation>) clss);
            if(annotInstance.annotationType().isAnnotation()) {
                fieldsWithAnnotations.add(field);
            }
        }
    }
    //clss =  clss.getSuperclass();
    return fieldsWithAnnotations;
}

If I get the size of the list that is returned by seekFieldsWithAnnotations, the size is always 0. When actually I was expecting it to be 2 because the fields firstName and email have annotations above them.

If I return the allFields list and get its size I get back 3 because there are three fields in the DummyUser class.

So I think the place where I am going wrong is

for(final Field field : allFields ) {
    // Here I am trying to check if annotations are present
    if(field.isAnnotationPresent((Class<? extends Annotation>) clss)) {
        Annotation annotInstance = field.getAnnotation((Class<? extends Annotation>) clss);
        if(annotInstance.annotationType().isAnnotation()) {
            fieldsWithAnnotations.add(field);
        }
    }
}





dimanche 29 mai 2016

Entity framework get related entites on SavingChanges

I need to get related entites while EF modify relations. I hook SavingChanges event of ObjectContext and getting an entry:

foreach (var entry in
                context.ObjectStateManager.
                    GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Deleted)
                    .Where(x => x.IsRelationship))
{
    var key0Prop = entry.GetType().GetProperty("Key0", 
        BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic);
    var key0 = ObjectContext.GetObjectByKey((EntityKey)key0Prop.GetValue(entry));
    var key1Prop = entry.GetType().GetProperty("Key1",
        BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic);
    var key1 = ObjectContext.GetObjectByKey((EntityKey)key1Prop.GetValue(entry));
}

The entry is internal RelationshipEntry class and I found only way - reflection. I understand this is probably unstable solution. Mybe where exist non reflection method to get related entities object while SavingChanges? Thanks.





How should i go about reflections in opengl?

As far as i know there are 2 ways,

1: "flip" the scene on the y axis and add some blending - Avoiding this since iv'e added deferred rendering, which doesn't support transparency without mixing with forward rendering.

2: render the scene to a cube map and do some stuff in the shaders - seems to be good for certain objects, but its a plane im trying to do reflections with.

any suggestions? Ive considered rendering the scene to an orthographic texture.





Reflection - restore time.Time instance

I am developing a program in go that needs to store and retrieve an array of custom structure instances using the sessions package of the Gorilla toolkit. For restoring the custom structure I need to make use of reflection features. The issue is that my structure named Timestamp includes two time.Time instances and I have not been able to restore the instances. Thus, my question is how to restore a time.Time instance.

Below you can see my code for the Timespan structure as well as the code for storing and reading the Timespan array in the session store.

type Timespan struct {
    ID uint8;
    StartDate time.Time;
    EndDate time.Time;
}

func (server *WebServer) setTimespans(writer http.ResponseWriter, request *http.Request, timespans [model.TimespanCount]*model.Timespan) error {
    var session *sessions.Session;
    var sessionDecodingException error;
    session, sessionDecodingException = server.SessionStore.Get(request, authenticationSessionName);
    if sessionDecodingException != nil {
        return sessionDecodingException;
    }


    session.Values[sessionTimestamps] = timespans;
    return nil;
}

func (server *WebServer) getTimespans(request *http.Request) ([model.TimespanCount]*model.Timespan, error) {
    var session *sessions.Session;
    var sessionDecodingException error;
    session, sessionDecodingException = server.SessionStore.Get(request, authenticationSessionName);
    var readTimespans [model.TimespanCount]*model.Timespan;
    if sessionDecodingException != nil {
        return readTimespans, sessionDecodingException;
    }

    interfaceValue := reflect.ValueOf(session.Values[sessionTimestamps]);
    var actuallyAddedTimespan *model.Timespan;
    for counter := 0; counter < model.TimespanCount; counter++ {
        actuallyAddedTimespan = &model.Timespan{};
        actuallyReflectedTimespan := interfaceValue.Index(counter).Elem();
        actuallyAddedTimespan.ID = uint8(actuallyReflectedTimespan.FieldByName("ID").Uint());
        //actuallyAddedTimespan.StartDate = actuallyReflectedTimespan.FieldByName("StartDate");
        //actuallyAddedTimespan.EndDate = actuallyReflectedTimespan.FieldByName("EndDate");
        fmt.Println(actuallyAddedTimespan);
    }
    return readTimespans, nil;
}





How to assign a value to a static field dynamically create objects?

I want to create an object using reflection class PropertyCondition(in assembly UIAutomationClient.dll).In order to obtain the desired class constructor , I use the following code:

        var assembly = AppDomain.CurrentDomain.GetAssemblies().First(x => x.FullName.Contains("AutomationClient"));

        var propertyConditionType = assembly.DefinedTypes.First(x => x.Name == "PropertyCondition");
        var automationElementType = assembly.DefinedTypes.First(x => x.Name == "AutomationElement");

        var automationIdPropertyType = automationElementType.GetField("AutomationIdProperty").FieldType;
        var constructor = propertyConditionType.GetConstructor(new Type[] { automationIdPropertyType, typeof(object) });

But how do I pass in constructor AutomationElement.AutomationIdProperty ?

Thank you.





samedi 28 mai 2016

java.lang.NoClassDefFoundError: scala/reflect/api/TypeCreator

I'm getting this error message when I run my sbt project in IntelliJ by right clicking "Debug".

/home/johnreed/Applications/jdk1.8.0_73/bin/java -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:34395,suspend=y,server=n -Dfile.encoding=UTF-8 -classpath /home/johnreed/Applications/jdk1.8.0_73/jre/lib/charsets.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/deploy.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/ext/cldrdata.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/ext/dnsns.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/ext/jaccess.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/ext/jfxrt.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/ext/localedata.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/ext/nashorn.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/ext/sunec.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/ext/sunjce_provider.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/ext/sunpkcs11.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/ext/zipfs.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/javaws.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/jce.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/jfr.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/jfxswt.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/jsse.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/management-agent.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/plugin.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/resources.jar:/home/johnreed/Applications/jdk1.8.0_73/jre/lib/rt.jar:/home/johnreed/sbtProjects/UnderstandingScala/target/scala-2.11/classes:/home/johnreed/.ivy2/cache/com.chuusai/shapeless_2.11/bundles/shapeless_2.11-2.3.1.jar:/home/johnreed/.ivy2/cache/org.scala-lang/scala-library/jars/scala-library-2.11.8.jar:/home/johnreed/.ivy2/cache/com.google.code.findbugs/jsr305/jars/jsr305-2.0.1.jar:/home/johnreed/.ivy2/cache/com.google.guava/guava/bundles/guava-16.0.1.jar:/home/johnreed/.ivy2/cache/com.twitter/jsr166e/jars/jsr166e-1.0.0.jar:/home/johnreed/.ivy2/cache/com.twitter/util-collection_2.11/jars/util-collection_2.11-6.34.0.jar:/home/johnreed/.ivy2/cache/com.twitter/util-core_2.11/jars/util-core_2.11-6.34.0.jar:/home/johnreed/.ivy2/cache/com.twitter/util-function_2.11/jars/util-function_2.11-6.34.0.jar:/home/johnreed/.ivy2/cache/commons-collections/commons-collections/jars/commons-collections-3.2.2.jar:/home/johnreed/.ivy2/cache/javax.inject/javax.inject/jars/javax.inject-1.jar:/home/johnreed/.ivy2/cache/org.scala-lang.modules/scala-parser-combinators_2.11/bundles/scala-parser-combinators_2.11-1.0.4.jar:/home/johnreed/.ivy2/cache/org.typelevel/macro-compat_2.11/jars/macro-compat_2.11-1.1.1.jar:/home/johnreed/.ivy2/cache/scala.trace/scala-trace-debug_2.11/jars/scala-trace-debug_2.11-2.2.14.jar:/home/johnreed/Applications/idea-IC-145.258.11/lib/idea_rt.jar pkg.Main
Connected to the target VM, address: '127.0.0.1:34395', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:34395', transport: 'socket'
Exception in thread "main" java.lang.NoClassDefFoundError: scala/reflect/api/TypeCreator
    at pkg.Main.main(Main.scala)
Caused by: java.lang.ClassNotFoundException: scala.reflect.api.TypeCreator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more

Process finished with exit code 1

I only get this error when I run from IntelliJ. When I run it from SBT with sbt run, it works fine. sbt compile works file too. How do I fix this so my project runs as an Application?





Create an instance of an unknown type

am pretty sure there is a few different ways of doing this, as i got very close to it without success with stuff like Activator.CreateInstance, but i wanted to see your opinion on my specific case.

Is there a way to avoid this kind of switches?

Resource r = null; <-- Resource is the base class of block,rock,plant types.

switch (type) //type is a byte you get from somewhere on runtime
{
    // Then you instantiate that class type depending on that "type byte", 
    // simply by comparing it to an enum lets say

    case ResourceType.Block:
        r = new Block();
        break;
    case ResourceType.Rock:
        r = new Rock();
        break;
    case ResourceType.Plant:
        r = new Plant();
        break;
}

//Then you apply some data to that newly created 'resource"
r.id = id;

//Then you save that 'resource' into a dictionary of resources.
ResourceDatabase.Add(r.id, r);





Issue translating data back from serialization into Go struct dynamically using reflection

I'm having trouble using reflection in Go to fetch data from a cache dynamically into various statically declared struct types:

func FetchFromCacheOrSomewhereElse(cacheKey string, returnType reflect.Type) (out interface {}, err error) {
    fetchFromCache := reflect.New(returnType).Interface();
    _, err=memcache.Gob.Get(*context, cacheKey, &fetchFromCache);

    if (err==nil) {
        out=reflect.ValueOf(fetchFromCache).Elem().Interface();

    } else if (err==memcache.ErrCacheMiss) {
        /* Fetch data manually... */

    }

    return out, err;

}

Reflect won't translate this statically typed cache data back into a reflect value, and returns this error instead: gob: local interface type *interface {} can only be decoded from remote interface type; received concrete type ... :\

This data is saved elsewhere in the code to the cache without the need for reflect.





Can't get reflect to not return pointers, compiler panics on conversion?

Code written around something like this is causing an issue:

func CreateNewItemOfType(returnType reflect.Type) (interface {}) {
    return reflect.New(returnType).Interface();

}

... How can one actually return a struct of returnType and not a pointer to a struct, as reflect creates here? The compiler builds this fine but panics at run-time, yet will not accept an asterisk in front of the return call here in order to actually return the struct and not a pointer.





Get pointer value via reflection

I have an instance of the type object, from which I know that it is a pointer (can easily be verified with myobject.GetType().IsPointer). Is it possible to obtain the pointer's value via reflection?

code so far:

object obj = .... ; // type and value unknown at compile time
Type t = obj.GetType();

if (t.IsPointer)
{
    void* ptr = Pointer.Unbox(obj);

    // I can obtain its bytes with:
    byte[] buffer = new byte[Marshal.SizeOf(t)];
    Marshal.Copy((IntPtr)ptr, buffer, 0, buffer.Length);

    // but how can I get the value represented by the byte array 'buffer'?
    // or how can I get the value of *ptr?
    // the following line obviously doesn't work:
    object val = (object)*ptr; // error CS0242 (obviously)
}





reflection - Get enum that is inside a class

I have a class with a enum in it and a constructor, that is using it as parameter.

public class Example {
  public enum ExampleEnum {WORK,IDLE};
  public Example(ExampleEnum e, String s){...}
  // Class body
}

But if I get enum value from it and pass it as argument to contstructor, I get java.lang.NoSuchMethodException

This is the code that I am using:

Object enumVal = Class.forName("Example$ExampleEnum").getField("WORK").get(null);
Object instance = Class.forName("Example").getConstructor(
        enumVal.getClass(),
        String.class).newInstance(
            enumVal,
            "test"
);

(The class exists)





vendredi 27 mai 2016

Gel all model attributes of a class in TypeScript

I have the following TypeScript class:

export class City {
  name: string;
  fullName: string;
  country: string;
  countryCode: string;
  center: GeoPoint;
}

I need a way of getting all model attributes in runtime. For example:

static init(obj): City {

    let city = new City();

    for (var i in obj) {
      if (i == "exists in City model") {
        city[i] = obj[i];
      }
    }
}

is there a simple way of doing this in TypeScript? I don't want to be required to maintain an array of all model attributes names to check this.





golang - how to access internals of struct (reflection?)

I need to add attributes to a log15 logger, but if I inadvertently add one twice it will appear twice. So, I want to add logic to see if the attribute is already populated and skip the action if it is.

Here's what I get when I output the log object:

log="&{ctx:[field1 val1 field2 val2 field3 val3 field2 val2] h:0xc82052c1e0}"

How can I access that 'ctx' field and validate when my value is already there? I've tried some reflection tricks and can get the data type, but I can't figure out how to get the value.





In Scala, How to get the returned TypeTag of a class method?

I have a class:

package org.apache.project

class Foo {

def bar: List[Bar] = ...
}

is it a way in scala reflection that allows me to get typeOf[List[Bar]] from the className "org.apache.project.Foo" and the method name "bar"?

Thanks a lot for your help!





Accessing / executing generic methods via reflection?

I'm trying to dynamically switch out my table annotations' schema values @ Runtime when using EF6.

So here's what I've got thus far:

var builder = new DbModelBuilder()
var dbSetProperties = typeof(T).GetProperties().Where(p => p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>));

foreach (PropertyInfo property in dbSetProperties)
{
    Type[] propTypes = property.PropertyType.GetGenericArguments();

    // Iterate the DbSets and set the correct schema
    foreach (Type dbSetType in propTypes)
    {
        // Get the TableAttribute
        var tableAttribute = Attribute.GetCustomAttribute(dbSetType, typeof(TableAttribute));

        MethodInfo dbModelMethodInfo = typeof(DbModelBuilder).GetMethod("Entity");
        MethodInfo entityTypeConfigMethodInfo = typeof(EntityTypeConfiguration<>).GetMethod("ToTable", new[] { typeof(String), typeof(String) });
        MethodInfo genericDbModelMethodInfo = dbModelMethodInfo.MakeGenericMethod(dbSetType);

        genericDbModelMethodInfo.Invoke(builder, null);
        entityTypeConfigMethodInfo.Invoke(genericDbModelMethodInfo, new Object[] { (tableAttribute as TableAttribute).Name, "NEW_SCHEMA_VALUE" });
    }
}

What I'm trying to accomplish is something like this (which doesn't work):

builder.Entity<dbSetType>().ToTable((tableAttribute as TableAttribute).Name, "NEW_SCHEMA_VALUE");

Basically, for T I want to pull the DbSets, determine the Class used in the Entity<> generic, get the TableAttribute, and set the Schema to a new value.

Currently, on entityTypeConfigMethodInfo.Invoke, I'm getting an error of "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true".

What am I missing?





Extract scala case class field

Given the following class:
case class Test(id: Long, name: String) { val details = Map("size" -> 54) }

How do i extract details without instantiating the class? I Know how to extract the id and the name using Scala reflection but can't figure out how to extract what i need.





modifying derived class values from base class

Is it possible to have a method in a base class to modify a derived class' properties? I was thinking something like this:

public class baseclass
{
  public void changeProperties(string propertyName, string newValue)
  {
    try
    {
      this.propertyName = newValue;
    }
    catch
    {
      throw new NullReferenceException("Property doesn't exist!");
    }
  }
}





Reflection C# get object from static property and set an instance property

Many examples such as

Set object property using reflection

Instantiate an object without reflection and then use it with reflection.

But how can the same thing be achieved with reflection to get the initial object?

My code so far is this

            var currentMethod = MethodBase.GetCurrentMethod();          
            string currentNamespace = currentMethod.DeclaringType.Namespace;
            string currentType = this.GetType().Name;
            var basetype = this.GetType().Assembly.GetType(currentNamespace + "." + currentType);
            PropertyInfo propertyInfo = basetype.GetProperty("Instance", BindingFlags.Public | BindingFlags.Static);            
            PropertyInfo propertyToSet = basetype.GetProperty(OutputVariableName, BindingFlags.Public | BindingFlags.Instance); 
            var val = propertyInfo.GetValue(propertyToSet, null);
            propertyToSet.SetValue(propertyInfo, Convert.ChangeType(prefix + suffix, propertyToSet.PropertyType), null);

This gives the error Object does not match the target type

I've also tried

            propertyInfo.SetValue(propertyToSet, Convert.ChangeType(prefix + suffix, propertyToSet.PropertyType), null);

Which gives the error Property set method not found.

The properties look like this:

    public static currentType Instance
    {
        get { return instance; }
    }

    public string NewTextName
    {
        get { return _NewTextName; }
        set { _NewTextName = value; }
    }

The intellisense for val shows all the properties and their current values, I'm expecting it to show just the property that has the name propertyToSet





How to iterate over all DbSet in a generic?

(I'm using EF6 here) Say I have an abstract class:

public abstract class MyContext<T> : DbContext

and let's put it to use:

public class MyTestContext : MyContext<MyTestContext>
{
    public DbSet<Object1> Object1 { get; set; }
    public DbSet<Object2> Object2 { get; set; }
}

Now, say I want to iterate over all the DbSets in MyTestContext, in my abstract class. Seems this would work (this is in a method in my abstract class):

var dbSetProperties = typeof(T).GetProperties().Where(p => p.PropertyType == typeof(DbSet<>));

Yet I get "Enumeration yielded no results".

What am I doing wrong here? Thanks!

edit Note - I don't expect to know the generic type arguments up front - I'm actually looking to determine what Types are in each of the DbSets.





Check if property inherit from type [duplicate]

This question already has an answer here:

I have:

class ViewModelBaseExtended<T> : NotifyPropertyChange, INotifyDataErrorInfo where T : ViewModelBaseExtended<T>
{

}

class ClassA : ViewModelBaseExtended<ClassA>
{
    public ClassB { get; set; }

    public ClassC { get; set; }
}

class ClassB : ViewModelBaseExtended<ClassB>
{

}

class ClassC
{

}

In constructor of ViewModelBaseExtended<T> i want to get all properties of this class and run some method with each property that inherit from ViewModelBaseExtended<T>

So when i instantiate ClassA it must find that public ClassB { get; set; } is inherit from ViewModelBaseExtended<T> and run some code. And ignore ClassC property because its not inherit from ViewModelBaseExtended<T>.

I try it like:

PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach (PropertyInfo p in properties)
    {
        var propertyType = p.PropertyType;

        if(typeof(propertyType).IsAssignableFrom(ViewModelBaseExtended<>))
        {
            //SUCCESS, do something
        }
        //else ignore this property
    }

Any ideas?





jeudi 26 mai 2016

golang get the reflect.Type of a type

Is it possible and how to get the reflect.Type of a type without creating an object from the type and calling on it reflect.TypeOf(obj)

What in java will be: MyType.class





VB.NET, why use reflection to get a value of an Objects property in this code

I've got a bit of sample code from the MSDN Magazine Dev 2008. "The ObservableCollection Class" by Ken Getz http://ift.tt/1ZNTfy9

It deals with raising and handling when a property value of a collection changes.

However, there's one bit I don't understand. The author uses reflection to obtain the Properties value of the affected Object in the collection. I don't understand why he does this when it can just be obtained by asking for the objects property value.

I suppose in the codes example the Author doesn't know which property has changed. I only need to monitor one property (name) so can I just grab it by calling myCustomer.name?

Is there another reason why refection is being used or is it just to generalise the code so it can show any change to any property in the class?

Private Sub HandlePropertyChanged( _
ByVal sender As Object, _
ByVal e As PropertyChangedEventArgs)

Dim propName As String = e.PropertyName
Dim myCustomer As Customer = CType(sender, Customer)

' Unfortunately, no one hands you the old property value, or the new 
' property value. You can use Reflection to retrieve the new property 
' value, given the object that raised the event and the name of the 
' property:
Dim propInfo As System.Reflection.PropertyInfo = _
  GetType(Customer).GetProperty(propName)
Dim value As Object =  propInfo.GetValue(myCustomer, Nothing)

MessageBox.Show(String.Format( _
  "You changed the property '{0}' to '{1}'", _
  propName, value))

End Sub





Getting map item with reflection

I'm trying to get a map value by its key using reflection:

HashMap<String, Float> myMap = new HashMap<String, Float>();
myMap.put("time", Float.valueOf(-1.7));
String param = "time";
//...
float modif = (float)myMap.getClass().getDeclaredMethod("get", String.class).invoke(myMap, param);

But I get this error notification:

java.lang.NoSuchMethodException: java.util.HashMap.get(java.lang.String)

Can anybody, please, suggest why?





Activator.CreateInstance and passing a boxed object to an invoked method

I have the following code ...

My Command handler:

public class MyHandler : IHandler
{
  // I Want to get rid of this method
  public override void ExecuteOperation(BaseOperation operation)
  {
    // This is a work-around
    this.ExecuteOperation(operation as SpecificOperation);
  }

  public override void ExecuteOperation(SpecificOperation operation)
  {
    // Do actual work here
  }
}

My Command handler dispatcher:

private dynamic FindOperationHandler(TBaseProvisioningOperation operation)
{
  ... some logic here
  return Activator.CreateInstance(handlerType, ... args here ...)
}

My consumer code

public void PerformProvisioningOperation(BaseOperation operation)
{
  // Find the correct handler for this operation
  var operationHandler = this.FindOperationHandler(operation as TBaseProvisioningOperation);

  // make it execute the operation
  // NOTE: 'operation' is SpecificOperation type, for example
  operationHandler.ExecuteOperation(operation); // <--- problem is here
}

The issue is that when I create an instance of my handler class with the Activator.CreateInstance and pass it a boxed object (i.e. as "BaseOperation") parameter, .NET looks for a method in the handler, which has a parameter of the base type, instead of automatically invoking the one which can handle the object if it were unboxed (i.e. explicitly cast).

Of course we have SpecificOperation : BaseOperation

In other words: I want when I execute operationHandler.ExecuteOperation(operation);, .NET to invoke ExecuteOperation(SpecificOperation operation) instead of ExecuteOperation(BaseOperation operation), because the operation parameter is boxed (i.e. it IS SpecificOperation but is downcast-ed as BaseOperation).

How do I achieve that?





mercredi 25 mai 2016

C++ Determine the type of a polymorphic object at runtime

I am trying to work on a project that will require me to determine a polymorphic object's type at runtime, so that I can cast it. An example of what I mean:

class A{
};
class B: public A{
    public:
        void foo(){
            printf("B::foo()\n");
        }
};

Later, I will have a bunch of B objects that are essentially stored as such:

std::vector<A*> v;
v.push_back(new B());

And I will need to call certain overloaded methods defined as:

void bar(B* b){
    b->foo();
}

After passing in objects that are stored in v. The problem that I am having is that in my actual use-case, I don't know the type of B at compile-time, so I can't just call bar by saying bar((B*)v.get(0));

The solution I have been thinking I might need is to somehow determine the type that each object is at runtime, so that I can cast it before passing it to bar.

The solution I have tried so far was to use decltype, but it didn't work for me because it just returns the static type of the value passed in, not the type at runtime.

Also, I do not want to use third party libraries for this project, since I would like to make it as small as possible.

Thank you for your help.





Java Reflection error trying to convert Field into WebElement

I'm struggling with i believe is a reflection problem.

Here is the thing, On my automation project I'm trying to create a helper class to validate Page Labels from my web application, to that i create a @annotation which contain just a label field.

It looks like this:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface ExpectedLabel{
    String label() default "";
}

At my Page Class i have the field:

@ExpectedLabel(label="Faça seu Login")
@FindBy(how = How.XPATH, using = "//*[@id='login']/form/h3")
private WebElement facaSeuLoginLabel;

And here is my helper class method to validate labels:

@SuppressWarnings("rawtypes")
public boolean validateLabels(Class validationClass){
    for (Field field: validationClass.getDeclaredFields()) {
        if(field.getType() ==  WebElement.class && field.isAnnotationPresent(ExpectedLabel.class)){
            field.setAccessible(true);
            ExpectedLabel expectedLabel = field.getAnnotation(ExpectedLabel.class);
            if (StringUtils.isNotBlank(expectedLabel.label())){
                try {
                    WebElement element = (WebElement) field.get(WebElement.class);
                    if(!StringUtils.equals(element.getText(), expectedLabel.label())){
                        LoggerUtil.warn("O campo "+field.getName()+" da Page "+validationClass.getSimpleName()+" tem um label invalido! Esperado : ("+expectedLabel.label()+") Obtido: ("+element.getText()+")!", validationClass.getSimpleName());
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return true;
}

The problem is, i have to call WebElement.getText() to have acess to the Real Page label and then compare to that one in the annotation @ExpectedLabel.label. Whatever I tried, just cant convert field into WebElement.

I already tried to create an implementation of WebElement called WebElementImpl and done the conversion, but still doesn't worked. Other approach that doesn't worked was trying to call the getText() method directly from Field, getting his public methods, but i don't think that is possible.

Here is the exception i get when tried to convert the objects:

java.lang.IllegalArgumentException: Can not set org.openqa.selenium.WebElement field com.org.pages.LoginPage.facaSeuLoginLabel to java.lang.Class
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:55)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:379)
    at com.org.helpers.LabelValidatorUtil.validateLabels(LabelValidatorUtil.java:20)
    at com.org.telas.LoginPageTest.loginPageValidationTest(LoginPageTest.java:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)

Obs: WebElement is an interface, so how can i make the conversion? New approaches to solve the problem are welcome.





Who to get the line number of a field declaration with Javassist?

This is a follow up to: How to get the line number of a method?

I have a java.lang.reflect.Field instance and want to know at which line the declaration was made of in the declaring class.

Currently I have a CtField but it lacks a getLineNumber() method ...

public static int getLineNumberOf(Class<?> type,Field field){
        ClassPool cp = ClassPool.getDefault();
        CtClass ctClass = cp.getCtClass(type.getName());
        CtField ctField = ctClass.getDeclaredField(field.getName());

        ctField.getLineNumber(); 
        //      ^^^^^^^^^^^^^^  that one is missing
}

What is the right way to get the line number?





MVEL vs reflection. What is generally faster regarding object member access?

What is generally faster regarding object member access?
1. Execute compiled mvel expression
2. Execute cached reflection method





mardi 24 mai 2016

Is there a way we can put the decorator /interceptor on all the objects that are being declared as field of a class?

I have a class Teacher which have two variables one is a collection of Student class and another is a Student class Object. I intercept the Teacher class as per my understanding all the objects under the Teacher class should have the interceptor attached to it. so for instance one we call a getter method on the Student variable retrieved from the Teacher class or from the list .It should call the intercept method is not called.This makes our axiom for design false.So my question is : Is there a way we can automatically intercept all the objects declared within the class and this could extend to the further down hierarchy within the tree? Below is the code :

//Teacher class

package com.anz.interceptorproject;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by mehakanand on 4/24/16.
 */public class Teacher {

    private String userName;
    private String cource;
    private List<Student> students=new ArrayList<Student>(  );

    public Student getComplexObjectStudent() {
    return complexObjectStudent;
}

    public void setComplexObjectStudent( Student complexObjectStudent ) {
    this.complexObjectStudent = complexObjectStudent;
}

    private Student complexObjectStudent=new Student();
    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getCource() {
        return cource;
    }

    public void setCource(String cource) {
        this.cource = cource;
    }
}

//Student Class

package com.anz.interceptorproject;

/**
 * Created by mehakanand on 4/24/16.
 */public class Student {

    private String name;
    private int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

//Interceptor Class
package com.anz.interceptorproject.change;
import java.lang.reflect.*;
import net.sf.cglib.proxy.*;
/**
 * Created by mehakanand on 4/24/16.
 */
public class ClassFacadeCglib implements MethodInterceptor{

    private Object target;

    public Object getInstance(Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        // callback method
        enhancer.setCallback(this);
        // create proxy object
        return enhancer.create();
    }


    public Object intercept(Object obj, Method method, Object[] args,
                            MethodProxy proxy) throws Throwable {
        Object res=null;

        if(method.getName().startsWith("set")){
            System.out.println(method.getName()+" start");
           res = method.invoke(target, args);

            proxy.invokeSuper(obj, args);
            System.out.println(method.getName()+" end..");
        }
        if(method.getName().startsWith("get")){
            System.out.println(method.getName()+" start");
             res = method.invoke(target, args);

            proxy.invokeSuper(obj, args);
            System.out.println(method.getName()+" end");
        }

        return  res;
    }

}

//Delegate class

package com.anz.interceptorproject;

import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;

import net.sf.cglib.proxy.MethodInterceptor;
import org.junit.Test;

public class SimpleUnitTest {
// this test is being used to test if when object is being intercepted will all its child object be intercepted automatically or not
    @Test
    public void TestifchildrenObjectIntercepted() {
        String proxyStudentName="";
        ClassFacadeCglib cglib=new ClassFacadeCglib();

        Student studentMehak=new Student();
        studentMehak.setAge( 30 );
        studentMehak.setName( "Mehak Anand" );
        Student studentComploexproxy=new Student();
        studentComploexproxy.setAge( 23 );
        studentComploexproxy.setName( "proxystudent Complex" );
        //let us assume the Teacher object is an object return from JCR after the adapTo() function is called on a resource
        Teacher teacher=new Teacher();
        teacher.setComplexObjectStudent( studentComploexproxy );
        teacher.getStudents().add( studentMehak );
        teacher.setCource("Math");
        teacher.setUserName("Mehak");
        teacher.getUserName();
        Teacher proxyTeacher=(Teacher)cglib.getInstance(teacher);

      / proxyTeacher.getClass().getDeclaredMethods();
        for (Student proxyStudentList:proxyTeacher.getStudents())
        {
            //the intercept method is not called.
            proxyStudentName= proxyStudentList.getName();
        }
        Student testComplexStudent=teacher.getComplexObjectStudent();
         assertEquals("Math",proxyTeacher.getCource());
        //the intercept method is not called
        testComplexStudent.getAge();

        System.out.println(  teacher.getUserName());

        assertTrue(true);
    }

}





Method is not working with reflection

One of my methods is not working which I used with both map and java reflection. I am not sure is it because of reflection or any other reason but it is working in other class where I didn't use reflection.

The method findAccessors() should retrieve a value from map2. The method is defined in the class ReadEdges. This method is called by another method findmethod() which is defined in the class FindMethod.

Whenever I call the method findAccessors() by the method findmethod(), it is returning an empty Linked List instead of returning the value from map2. The classes are given below:

Class ReadEdges :

import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

public class ReadEdges {
    static DFSclass dfs = new DFSclass();
    List<String> sourcenodes=new ArrayList<String>();  // source node
    List<String> destinationnodes=new ArrayList<String>(); // destination node
    LinkedHashSet<String> findtransitions=new LinkedHashSet<String>();
    LoanApprovalSystem LS = new LoanApprovalSystem();
    TestdataGeneration testdata = new TestdataGeneration();

    private static final String edgePat = "([a-zA-Z]|[0-9])+(,|\\x20)([a-zA-Z]|[0-9])+";
    private static final String start=dfs.getstart();
    private static final String edge = dfs.getedge();
    private static final String transitions=dfs.gettransitions();
    public static String a;
    public static String b;
    public static String c;
    public static String d;
    private Map<String, LinkedHashSet<String>> map = new HashMap();
    private Map<String, LinkedHashSet<String>> map2 = new HashMap();

     public int getLineCount(String edge){
         int count = edge.split("[\n|\r]").length;
         //System.out.println(count);
            return count;
        }


     public void addEdge(String node1, String node2) throws IOException{

         LinkedHashSet<String> adjacent = map.get(node1);
         {
            if(adjacent==null) {
                adjacent = new LinkedHashSet();
                map.put(node1, adjacent);
            }
            adjacent.add(node2);            
         }

        }

     public void addedgeandAccessor(String edge, String accessor) throws IOException{
         LinkedHashSet<String> adjacent2 = map2.get(edge);
         {
            if(adjacent2==null) {
                adjacent2 = new LinkedHashSet();
                map2.put(edge, adjacent2);
               //System.out.println(map2);
            }

            adjacent2.add(accessor);
            //System.out.println(map2);
         }
     }

    public void ReadEdge(String edgeinput,String transitionsinput,String accessorinput) throws InvalidInputException
    {
        char[] buf = edgeinput.toCharArray();
        BufferedReader br = new BufferedReader(new CharArrayReader(buf));

        char[] buf2 = transitionsinput.toCharArray();
        BufferedReader br2 = new BufferedReader(new CharArrayReader(buf2));     
        String str2 = null;

        char[] buf3 = accessorinput.toCharArray();
        BufferedReader br3 = new BufferedReader(new CharArrayReader(buf3));     
        String str3 = null;

        try 
        {
            //a string for a next edge
            String str = null;
            //a StringTokinizer
            StringTokenizer newNodes = null;
            //get edges and set edges for the graph
            while((((str = br.readLine()) != null) && (str2 = br2.readLine()) != null) && ((str3 = br3.readLine()) != null))
            {
                c=str;
                d=str2;


                LinkedHashSet<String> adjacent = map.get(str);
                if(adjacent==null) {
                    adjacent = new LinkedHashSet();
                    map.put(str, adjacent);
                }
                adjacent.add(str2);

                addedgeandAccessor(str,str3);

                //if the edge inputs are not in good format, throw the exception
                if(!Pattern.matches(edgePat, str.trim()))
                    JOptionPane.showMessageDialog(null,"An invalid input '" + str + "' for an edge. Please read the notes above the forms. ");
                //use a comma to separate tokens
                newNodes = new StringTokenizer (str, ", ");
                //get the value of source node of an edge
                String src = newNodes.nextToken();
                //create the source node and destination node 
                String srcNode = src;
                String desNode = newNodes.nextToken();

                a=srcNode;
                b=desNode;


                addEdge(srcNode, desNode);  
                //System.out.println(adjacent);             
                //findTransition(a,b);
                //findAccessors(a,b);

            }

            //System.out.println(listoftransitions);
        }
            catch (IOException e) {
                JOptionPane.showMessageDialog(null, "Something is Wrong!");
                e.printStackTrace();
            }
}


    public LinkedList<String> adjacentNodes(String last) {
        LinkedHashSet<String> adjacent = map.get(last);
        if(adjacent==null) {
            return new LinkedList();
        }
        return new LinkedList<String>(adjacent);

    }

    public LinkedList<String> findTransition(String node1, String node2) throws IOException{

            LinkedHashSet<String> adjacent = map.get(node1+" "+node2);
            if(adjacent==null) {
                return new LinkedList();
            }
            findtransitions = adjacent;
        return new LinkedList<String>(findtransitions);

    }

    public LinkedList<String> findAccessors(String node1, String node2) {
        LinkedHashSet<String> adjacent = map2.get(node1+" "+node2);
        if(adjacent==null) {
            return new LinkedList();
        }
        System.out.println(adjacent);
        return new LinkedList<String>(adjacent);

    }

public String getsrcNode(){
    return a;
}

public String getedgeline(){
    return c;
}

public String gettransitionline(){
    return d;
}

}

Class FindMethod :

import java.util.ArrayList;
import java.util.LinkedList;
import java.lang.reflect.*;

public class FindMethod {

    ReadEdges r = new ReadEdges();
    LoanApprovalSystem LS = new LoanApprovalSystem();
    TestdataGeneration testdata = new TestdataGeneration();


    int method1;
    String method2;
    boolean method3;
    boolean method4;
    String method5;
    String m;


    //returns the method name using refletion
    public String getmethod(Method method){

        FindMethod fm = new FindMethod();
          m = method.getName();         
          String str = "";           

                 str += m+"(" +fm.getparameter(method)+ ")";
               // System.out.println(str);

          return str;
    }


    //returns the parameter name of the method using refletion (i.e. (int))
    public String getparameter(Method method){

        String str = "";
        Class<?>[] params = method.getParameterTypes();
         for (int i = 0; i < params.length; i++) {
             if (i > 0) {
                 str += ", ";
             }
             str += (params[i].getSimpleName());
         }
         return str;
    }

public void findmethod(String s,String t,String transition) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{

        FindMethod fm = new FindMethod();


        LoanApprovalSystem cls = new LoanApprovalSystem();
        Class<? extends LoanApprovalSystem> c = cls.getClass();
        Object obj = c.newInstance();
        Method[] methods = LoanApprovalSystem.class.getMethods();


          for(Method method : methods)
          {
              //returns the method name (i.e. Receive or Asses)
              m = method.getName();
              fm.getmethod(method);


        if(transition.equals(fm.getmethod(method)) && (transition.equals("Receive(int)")) )
        {
            if(fm.getparameter(method).equals("int") )
            {
                //LS.Receive(testdata.TestData(s,t));
                //invoking the method at runtime where m="Receive".

                method = c.getMethod(m, int.class);
                method.invoke(obj,testdata.TestData(s,t));

                LinkedList<String> accessors= r.findAccessors(s,t);
                System.out.println("A:"+accessors);

                method1=LS.getamount();

                System.out.println(m+"("+method1+")");
                System.out.println("Amount: "+method1);
            }
        } 

}
    }

     public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException
     {
         FindMethod fm = new FindMethod();
         fm.findmethod("1","2","Receive(int)");
     } 
}

Can anybody please tell me why my method findAccessors() is not working within the method findmethod()? Or please give me a solution of this problem.

Note: There is another class used in this program LoanApprovalSystem (). If anyone need I can give the definition of that class too.





How to change a value inside a third party library

(You don't need to know android to help solve this question)

I am using a third party library in my android app. Call it libX. libX has a class named Constants in which they keep a number of constants. One such constant is used all over inside the library. But I need the value of that constant to be different from what it is. How do I change the value of that constant?

As illustration: I want to change the value of badConstant from “I am too bad” to “I am good”.

class Constants{
  public static final String badConstant = “I am too bad”;
}

I am open to any sort of creative solution. The thing is if I had a setter/constructor for the value all would be well. But right now there is no setter.

Also this library is obtained as a gradle dependency (if you care)





How to programmatically change all property values of an object based on a regex [duplicate]

This question already has an answer here:

I am trying to change all properties of a generic object. For example I have some object X which has properties X.msg:string and X.msg2:string (Again I am dealing with generic types). I specifically want to change all string properties of my object as many contain an expression such as: "Hello <br> this </br> is a test". I want to remove all occurrences of <br> and <\br>. Here is my approach:

var item = T; // item is some generic object

foreach(PropertyInfo propertyInfo in item.GetType().GetProperties(BindingFlags.Public)){
    propertyInfo.SetValue ... // not sure what to do here to change value

I am new to reflection and I'm not quite sure how I can alter these values.

EDIT: My better attempt at the set value function is:

propertyInfo.SetValue (item, propertyInfo.GetValue(item) .ToString ().Replace ("</br>", ""));

But that doesn't work (does not remove the </br>)





Custom converters in Scallop library

I am trying to use Scallop (http://ift.tt/1OUygcy) to parse the command-line arguments in Scala.

However, I cannot compile the example for converting arguments to a case class as shown on http://ift.tt/1UbUKot.

I get two errors at compile-time:

[error]  found   : org.rogach.scallop.ValueConverter[center.scala.sbk.Commands.Person]{val nameRgx: scala.util.matching.Regex; val phoneRgx: scala.util.matching.Regex}
[error]  required: String
[error] Error occurred in an application involving default arguments.
[error]     val person = opt[Person](personConverter)
[error]                              ^

and

[error] ...: could not find implicit value for parameter conv: org.rogach.scallop.ValueConverter[center.scala.sbk.Commands.Person]
[error] Error occurred in an application involving default arguments.
[error]     val person = opt[Person](personConverter)
[error]                             ^

Thank you for your help!





C# code trying to open New Outlook Mail Automatically. Error 0x80020006 (DISP_E_UNKNOWNNAME)

I'm trying to open Outlook NewMail with C# code (without COM) but unfortunately I obtain the following error code:

0x80020006 (DISP_E_UNKNOWNNAME)

The c# code is just below.


using System;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;
using Erp.Adapters;
using Erp.UI;
using Ice.Lib;
using Ice.Adapters;
using Ice.Lib.Customization;
using Ice.Lib.ExtendedProps;
using Ice.Lib.Framework;
using Ice.Lib.Searches;
using Ice.UI.FormFunctions;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Linq;
using Microsoft.CSharp;
using System.IO.Compression;
using System.Reflection;
using System.Text;
using System.IO;

public class Script
{
    // ** Wizard Insert Location - Do Not Remove 'Begin/End Wizard Added Module Level Variables' Comments! **
    // Begin Wizard Added Module Level Variables **

    // End Wizard Added Module Level Variables **

    // Add Custom Module Level Variables Here **

    public void InitializeCustomCode()
    {
        // ** Wizard Insert Location- Do not delete 'Begin/End Wizard Added Variable Initialization' lines **
        // Begin Wizard Added Variable Initialization


        this.POForm.AfterToolClick += new Ice.Lib.Framework.AfterToolClickEventHandler(this.POForm_AfterToolClick);
        // End Wizard Added Variable Initialization

        // Begin Wizard Added Custom Method Calls

        // End Wizard Added Custom Method Calls
    }

    public void DestroyCustomCode()
    {
        // ** Wizard Insert Location - Do not delete 'Begin/End Wizard Added Object Disposal' lines **
        // Begin Wizard Added Object Disposal


        this.POForm.AfterToolClick -= new Ice.Lib.Framework.AfterToolClickEventHandler(this.POForm_AfterToolClick);
        // End Wizard Added Object Disposal

        // Begin Custom Code Disposal

        // End Custom Code Disposal
    }

private void POForm_AfterToolClick(object sender, Ice.Lib.Framework.AfterToolClickEventArgs args)
    {
    if(args.Tool.Key == "EmailFaxTool")
{

Assembly interopAssembly = Assembly.LoadFile(@"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14\Microsoft.Office.Interop.Outlook.dll");

 object outlookApplication = interopAssembly.CreateInstance("Microsoft.Office.Interop.Outlook.ApplicationClass");
 Type outlookApplicationType = interopAssembly.GetType("Microsoft.Office.Interop.Outlook.ApplicationClass");



dynamic mailItem = outlookApplicationType.InvokeMember("CreateItem", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, outlookApplication, new object[] { 0 });


//ADDRESS
//object recipients = outlookApplication.GetType().InvokeMember("Recipients",BindingFlags.GetProperty, null, outlookApplication, null);
//string To = "gregory.dupuy@consultencia.com";
//object[] address = new object[1];
//address[0] = To;

//SUBJECT1
//recipients.GetType().InvokeMember ("Add", BindingFlags.InvokeMethod,null, recipients, address);
//string subject = "Mail Message Subject";
//parms [0] = subject;

//SUBJECT
//outlookApplication.GetType().InvokeMember("Subject", BindingFlags.SetProperty,null, outlookApplication, new object[] { 0 });
//string msg = "Just a message saying hello";


//BODY
//outlookApplication.GetType().InvokeMember("Body", BindingFlags.SetProperty,null, outlookApplication, new object[] { 0 });

//DISPLAY OR SEND
// Invoke the Send method of the mail item.
outlookApplication.GetType().InvokeMember("Display", BindingFlags.InvokeMethod,null, outlookApplication,new object[] { true } );


{
throw new Exception("OK.");
}
}

}
}





Java: Calling a method by reflection in a functional interface

does anyone know, if i can invoke a method by reflection in the body of a functional interface?

I want to return a predicate. So the typical syntax would be for example

Predicate<Data> pred = data -> data.getVar1().equals("foobar");

But in my special case neither the class nor the method to call is known since it's variable.

So I wanted to get something like this:

Method method = Class.forName("Data").getMethod("getVar1", (Class[]) null);
Predicate<T> pred = data -> 
                  ((String) method.invoke(data, (Object[]) null)).equals("foobar");

But Eclipse says: "Not handled TargetInvocationException". So I surrounded it with try-catch, but Eclipse shows already the same message.

Does anyone have a clue for me?





Mapper for POJOs in Java

I am writing a mapper to map fields of 2 different POJOs in java. I have used Dozer mapper for simple mapping but in this case, I have a slightly complex strategy when it comes to set the value to the destination object. The getter is simple, but instead it setting it directly, I want to do some processing on the value.

My question is, can I use dozer mapper for my cause? In case if its not possible, is it ok (from performance point of view) to use reflection to implement my own mapper (this is because I have defined the mapping in an xml file and dont want to hardcode it in the mapper class)?

<mapping>
  <field>
   <!-- source -->
   <field-a name="cat">
   <!-- destination -->
   <field-b" name="dog">
  </field>
</mapping>

Relevant to this xml, I want the following:

Source c;
Destination d;
d.setDog(someProcessing(c.getPsMessage()));

Note down the extra processing (someProcessing) after getting the value and before setting it to the destination object.





Why do I get NoSuchMethodException?

I keep getting NoSuchMethodException in this line:

float modif = (float)sc.affectingObject.getClass().getMethod(sc.affectingMethodName, (Class<?>[])null).invoke(sc.affectingObject, (Object[])null);

where sc is an instance of class SubChange:

class SubChange implements Serializable {
    String changeType;
    Serializable affectingObject;
    String affectingFieldName;
    String affectingMethodName;

    public SubChange(String chanType, Serializable affingObj, String affingFM) {
        try{
            changeType = chanType;
            affectingObject = affingObj;
            //deciding whether affingFM provides a field name or a method name
            for (Field f : affingObj.getClass().getDeclaredFields()) {
                if (f.getName().equals(affingFM) == true) {
                    affectingFieldName = affingFM;
                    break;
                }
            }
            if (affectingFieldName == null) {
                affectingMethodName = affingFM;
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    //other class methods
}

whose instance has been initialized like this:

new SubChange("first", physio, "calcTotalFatigue")

where physio is an instance of inner class belonging to class Hm, while the SubChange constructor is being called from another inner class of the same Hm class.

Needless to say that method calcTotalFatigue() of physio exists.

Can anyone, please, suggest what I am doing wrong?





lundi 23 mai 2016

Instantiating an Object using Java Reflection

I am testing a private method using JUnit and I am invoking it using Reflection. The error I am getting is java.lang.InstantiationException. I know it is not creating an instance of Class but I am not sure what I am doing wrong. Object object = clazz.newInstance(); is the line that throws Exception.

Method under test

 private int _getType(String type) {
    if ("DATE".equalsIgnoreCase(type)) return Types.DATE;
    if ("STRING".equalsIgnoreCase(type)) return Types.VARCHAR;
    if ("INT".equalsIgnoreCase(type)) return Types.INTEGER;
    if ("TIMESTAMP".equalsIgnoreCase(type)) return Types.TIMESTAMP;

    return Types.NULL;

}

JUnit test

@Test
public void testGetType() throws Exception {
    String type1 = "DATE";
    String type2 = "STRING";
    String type3 = "INT";
    String type4 = "TIMESTAMP";

    Class clazz = SpringStoredProcImpl.class;
    Object object = clazz.newInstance();

    Method method = object.getClass().getDeclaredMethod("getType", String.class);
    method.setAccessible(true);

    method.invoke(object, type1);

I don't have my asserts yet so please ignore it.

Thanks in advance.





How to avoid .Else { .Default(System.Void) } in Expression.IfThen() results?

I use Expression Trees and want to get maximum performance from it. The common code is

ConstantExpression const1 = Expression.Constant(1);
ConstantExpression const2 = Expression.Constant(2);
BinaryExpression equality = Expression.Equal(const1, const2);
Expression ifTrue = Expression.Constant("I throw some exception here");

ConditionalExpression result = Expression.IfThen(equality, ifTrue);

The result.DebugView is .If (1 == 2) { "I throw some exception here" } .Else { .Default(System.Void) }

Is that possible to avoid

.Else { .Default(System.Void) }?

I mentioned this issue too late, and changes Expression.IfThen to Expression.IfThenElse require too many refactoring.

Compiler can make some code improvements in the release mode. Does it relate to expression trees too?





Find shared type among set of values

Given a passed-in IEnumerable<object>, is there any built-in method to return a best-matching base type for all the items in the IEnumerable, that handles nullable/non-nullable types and inheritance?

(I am aware that I can write my own; my question is if there is something built-in).





dimanche 22 mai 2016

C# Model to Dictionary

I have been scouring the internet but still haven't found what I'm looking for ( what U2? ). Enough of that, what I am looking for is an intuitive way to parse a poco ( complex with Lists, nullables etc ) to a Dictionary to be stored in a key/value database and then a means to re-populate the model back. In essence I am trying to achieve what the MVC model binder does when it maps from form parameters to a model, but them be able to do the reverse as well. I have tried digging into the source but it requires all the dependencies of a controller and I dont really want that. here is some source as an example

public class Item
{
    public string Name { get; set; }
    public decimal? Amount { get; set; }
    public List<RowItemModel> Items { get; set; }
}

public class RowItemModel
{
    public string Description { get; set; }
    public decimal Amount { get; set; }
}

So there is the model, and here is what I would like the outcome to look like :

P.S. : Note I have added a prefix for demarcation purposes in the db -> "Item."

Item.Name : The Name Here
Item.Amount : 0.0
Item.Items[0].Description : Description Here
Item.Items[0].Amount : 50
Item.Items[1].Description : Second Description

As you can see, it follows the exact same naming conventions as you would use when creating form elements for binding to a model ( using MVC ). What I am looking for is an elegant way to bind to the model from that ( dictionary ) and then to generate the dictionary from the populated model.

I have already achieved this using some really ugly string manipulation and then basic reflection combined with recursion, but it's leaving me with a bad taste in my mouth and I can't bring myself to push it to production, so any frameworks / elegant solutions would be appreciated.





Why am i getting a stackoverflow error when i try to get a object from a field using java reflection?

I'm trying to get fields from a JFrame class and separate those field objects by their type.Then im gonna put those separated objects into different Sets. But when i run the code, i'm getting a StackOverFlowError. I don't know what i'm doing wrong. Anyway this is my first time using java reflection, therefore i cannot be 100% sure that those particular code lines are suitable for get the necessary output. Please help me guys. Appreciate it. This is the code.

    public class SkinAnalyser {

private Set<JLabel> lblSet;
private Set<JTextField> txtSet;
private Set<JPanel> pnlSet;
private SkinColorInitializer clrInit;


    public SkinAnalyser(Field[] fields) throws IllegalArgumentException, IllegalAccessException{
        lblSet = new HashSet();
        txtSet = new HashSet();
        pnlSet = new HashSet();

        for (Field field : fields) {
            field.setAccessible(true);

            if(field.getType().isAssignableFrom(JLabel.class)){

                lblSet.add((JLabel)field.get(new EditUser()));
            }else if(field.getType().isAssignableFrom(JTextField.class)){

                txtSet.add((JTextField)field.get(new EditUser()));
            }else if(field.getType().isAssignableFrom(JPanel.class)){

                pnlSet.add((JPanel)field.get(new EditUser()));
            }
        }
    }
}





Reflection and recursion in array - StackOverflowException

I have two class :

public class Customer
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public bool isActif { get; set; }

    public Product[] Product { get; set; }
}

public class Product
{
    public string Id { get; set; }
}

And two instances :

Customer Customer1 = new Customer
{
    FirstName = "FirstName1",
    LastName = "LastName1",
    isActif = true,
    Product = new Product[]
    {
        new Product()
        {
            Id = "1"
        }
    }
};

Customer Customer2 = new Customer
{
    FirstName = "FirstName2",
    LastName = "LastName2",
    isActif = false,
    Product = new Product[]
    {
        new Product()
        {
            Id = "2"
        }
    }
};

I have one method who compare all properties of the two instances :

public static bool AreEquals(object objectA, object objectB)
{
    if (objectA == null && objectB == null)
        return true;

    if (objectA != null && objectB != null)
    {
        Type objectType = objectA.GetType();

        foreach (PropertyInfo propertyInfo in
                 objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(x => x.CanRead))
        {
            object valueA = propertyInfo.GetValue(objectA, null);
            object valueB = propertyInfo.GetValue(objectB, null);

            if (typeof(IComparable).IsAssignableFrom(propertyInfo.PropertyType) ||
                propertyInfo.PropertyType.IsPrimitive ||
                propertyInfo.PropertyType.IsValueType)
            {
                if (!AreValuesEqual(valueA, valueB))
                    Console.WriteLine(propertyInfo.ReflectedType.Name + "." + propertyInfo.Name + " not equal");
            }
            else if (!AreEquals(valueA, valueB))
                return false;
        }
        return true;
    }
    return false;
}

But when I get to the property Product, I have an StackOverflowException generated. Why ? And how to loop the property if it is a array ?





ClassNotFoundException on static inner class

I'm getting a ClassNotFoundException using Class.forName() passing the fully qualified name of a public static class that lives inside the same package. This is when running my tests.

Here's the full stacktrace.

In EntitySerializerTests.java inside my tests folder.

package com.badlogic.ashley.serialization;
public class EntitySerializerTests {

    public static class TestComponentA implements Component {
        public int value;
    }

    ...
}

In my library code

package com.badlogic.ashley.serialization;
public class EntitySerializer implements Json.Serializer<Entity> {
    ...

    private Component read(Json json, JsonValue componentValue) throws ClassNotFoundException {
        String className = componentValue.name();
        Class componentType = Class.forName(className); // THROWS
        ...
    }
}

The exception message is:

java.lang.ClassNotFoundException: com.badlogic.ashley.serialization.EntitySerializerTests.TestComponentA

Library code is trying to get the Class given the name for a class that's defined in a test file. Is that allowed? I would assume that, at runtime, all these classes are available in the class path.

Thanks.





samedi 21 mai 2016

Gradle - Can't access class fields

I am creating a gradle plugin in groovy, but I can't access the fields of the class. Here's what I have:

public class MyPlugin implements Plugin<Project> {
  void apply(Project project) {
     project.extensions.create("myClass", MyClass)
     ....
     println project.myClass.getClass().getName()
     ....
     println field.getName()
     println field.getType()
     ...         
  }
}

class MyClass {
  @MyAnnotation("Hello world")
  String myFeild
}

Output

MyClass_Decorated
__$stMC
boolean

Expected

MyClass
myField
String





Java reflection: getting constructor fails for inner-class

I have a class, named GlowZombie, which has two contructors:

public class GlowZombie extends GlowMonster implements Zombie {

    public GlowZombie(Location loc) {
        this(loc, EntityType.ZOMBIE);
    }

    public GlowZombie(Location loc, EntityType type) {
        super(loc, type, 20);
    }

And that class has a subclass, GlowHusk, with the same constructor parameters:

    public class GlowHusk extends GlowZombie implements Zombie.Husk {

        public GlowHusk(Location loc) {
            this(loc, EntityType.HUSK);
        }

        public GlowHusk(Location loc, EntityType type) {
            super(loc, type);
        }
    }
}

Then, I need to use reflection to get the GlowHusk(Location) constructor, like such:

Constructor<T> constructor = (Constructor<T>) GlowZombie.GlowHusk.class.getConstructor(Location.class);

...Which throws exception:

java.lang.NoSuchMethodException: net.glowstone.entity.monster.GlowZombie$GlowHusk.<init>(org.bukkit.Location)

Note:

Using GlowZombie instead of GlowHusk executes correctly:

Constructor<T> constructor = (Constructor<T>) GlowZombie.class.getConstructor(Location.class);

And does not throw an exception.

The question: why does getConstructor() not work in this scenario? Would it be because it is an inner-class, thus requiring some other way of accessing it?





How to query over an entity with a class name is a string?

Is there a way to query over an entity if the entity name is given as a string? In the example below it is obvious that the "className" needs to be converted to the target class, but i could not figure out how to do that by reflection...

private TEntity GetEntity(string className, Guid id)
{

     var entity = Session.QueryOver<className>().FirstOrDefualt(e => e.Id == id);

     return entity;

}





f# Using Reflection.Emit to generate Discriminated Unions

I would like to know if it was possible to generate a DU in f# using Reflection.emit (or anything else there is out there) or even add new cases to an already defined DU.

I have been looking at the msdn website, and I found out that all I can do is to get union cases or create union cases. Either by using FSharpValue.MakeUnion or using quotations with Expr.NewUnionCase to create them.

The issue I have with using this methods is how would I be able to bind them in such a way that the union cases I have made belong to the same DU? Maybe that is not the right to way to undertake this problem. In that case how would I generate DU dynamically?

P.S: The goal would be to generate DUs inside a Type provider. This would mean, if I am not wrong, that when compiled into a .dll file, I would be able to access the DU generated by the TypeProvider inside a script file. Thus meaning that I would be able to apply pattern matching over an instance of the DU, and also get the type safety provided by the DU (exhaustiveness of all the cases in a pattern matching for instance).

Thank you for your time !!!





vendredi 20 mai 2016

Issues with collection of Dynamically typed service classes & objects

We are building data structure migration system that should be capable of migrating from any version of a case class to the latest one; as well as from the latest version to any one of the previous ones. The concept is as follows:

We have a structure of case classes and migration classes

v1/SchemaV1 <= Case class V1
v2/SchemaV2 <= Case class V2
v2/MigrationV2 <= Migration Class from 1->2 and back
v3/SchemaV3 <= Case class V3
v3/MigrationV3 <= Migration Class from 2->3 and back
...

Where:

  • case classes can potentially be anything, however they are implementing the same interface Schema
  • Migration classes implement Migration trait and must implement 'up' and 'down' methods that simply convert one object into another.

Currently Migration trait looks like this:

trait TypedMigration[F <: Schema, T <: Schema] {

  type FromSchema = F
  type ToSchema = T

  /**
    * This method is responsible for migrating one version of a schema 'F'(From) to another 'T' (To)
    *
    * @param from
    * @return
    */
  def up(from: FromSchema): ToSchema

  /**
    * This method is responsible for migrating one version of a schema down one level
    *
    * @param from
    * @return
    */
  def down(from: ToSchema): FromSchema
}

The idea here, that every implementation of migration class will have from and to types enforced.

As an example:

class V2Migration extends TypedMigration[v1.SchemaV1, v2.SchemaV2] {
   ...
}

How, there is a service class the responsible for managing this whole migration process. This class has two methods that handles migrations 'up' & 'down' respectively

As an example:

protected[versioning] def doMigrateUp(schema: Schema): ChecklistSchema = {

    // load all required migration classes
    val migrations = loadMigrationObjects[Schema, Schema](resolveSchemaVersion(schema), targetVersion)

    var migratedSchema = schema
    // apply all migrations up
    migrations.foreach { migration =>
      migratedSchema = migration.up(migratedSchema)
    }

    migratedSchema.asInstanceOf[ChecklistSchema]
  }

Where:

  • `loadMigrationObjects' method returns a list of migration objects in order
  • ChecklistSchema is a type alias to the latest version. So I can safely cast to it at the end.

All good till now...

The problem for me begins in the 'doMigrateDown` method:

protected[versioning] def doMigrateDown[S <: Schema](schema: ChecklistSchema, targetVersion: Int): S = {
    val migrations = loadMigrationObjects[Schema, ChecklistSchema](resolveSchemaVersion(schema), targetVersion)

    var migratedSchema = schema
    // apply all migrations down
    migrations.foreach { migration =>
      migratedSchema = migration.down(migratedSchema)
    }

    migratedSchema.asInstanceOf[S]
  }

Here, there are two problems:

  1. I am getting compilation error: enter image description here

  2. I am not sure if this casting can actually work.

I this point I am totally stuck...

For the reference, this is how we build the list of migration objects:

protected[versioning] def loadMigrationObjects[F <: Schema, T <: Schema](currentVersion: Int, targetVersion: Int): List[TypedMigration[F, T]] = {

    val migrationsRange = if (currentVersion <= targetVersion) {
      currentVersion + 1 to targetVersion
    } else {
      currentVersion to targetVersion + 1 by -1
    }

    val migrations = List[TypedMigration[F, T]]()

    migrationsRange.foldLeft(migrations) { case (acc, versionNumber) =>
      Try {

        val migrationClassName = MigrationClassNameFormat.format(versionNumber, versionNumber)
        Class.forName(migrationClassName).newInstance().asInstanceOf[TypedMigration[F, T]]

      } match {
        case Success(m) => acc :+ m
        case Failure(e: ClassNotFoundException) =>
          logger.info("migration class was not found", e)
          acc
        case Failure(e) => throw e
      }
    }

  }





(Java) Access a subclass field with reflection

I have this code :

class A
{

    private void update()
    {
        Field theField = this.getClass().getDeclaredField("myField");

        theField.setAccessible(true);
        theField.set(this, "New Value");
    }

}

class B extends A
{
    private String myField = "hey";
}

But, it throws a IllegalAccessException :

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

I know this code is ugly, but this is for automatically fill a field with an annotation. I don't know how to do that, maybe with Unsafe but I need the memory address of the field.

Thanks you for any help.





Using Ninject create an instance of an interface

In our middleware, interfaces are bound in Global.asax.cs. I created a HandshakeInvoker that reflects through all FieldInfo until it finds an interface that implements IESFPingable. When it finds one i need to create an instance of that interface which will then call the ping() class in the provider. My problem is I am having trouble creating the interface once it finds a match.

Global.asax.cs binds:

kernel.Bind().To().InSingletonScope();

HandshakeInvoker:

public object Invoke(object instance, object[] inputs, out object[] outputs)
{
    outputs = new object[0];
    Type interfaceType = typeof(IESFPingable);

    FieldInfo[] fields = serviceType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
    foreach (FieldInfo f in fields)
    {
        if (interfaceType.IsAssignableFrom(f.FieldType))
        {
            Console.WriteLine("  >> Field {0} Implements {1}", f.fieldType.Name, interfaceType.Name);
            var interfaceToPing = kernal.Get<f.FieldType.Name>();
        }
    }
    return DateTime.Now;  //return date for now
}

I get errors: The Name 'kernel' does not exist in the current context and The type or namespace name 'f' could not be found (are you missing a using directive...)

Does anyone see what i am doing incorrectly? All help greatly appreciated.