mardi 31 octobre 2017

there are some fields else when use Java reflect to get fields

I used APIModel.getClass().getDeclaredFields() to get fields,but as a result there are some fields else:

org.codehaus.groovy.reflection.ClassInfo@1d9b76bf

FALSE

groovy.lang.MetaClassImpl@5fd1f73a[class APIModel]

java.lang.ref.SoftReference@62e2dc91

I have no idea...





Matching TypeTag with another field in a case class

Is there a way I can make following piece of code work? Expected result is that one of the promises in the list will be completed (the one with matching String type).

import scala.concurrent.Promise
import scala.reflect.ClassTag

case class Test[T](promise: Promise[T], tag: ClassTag[T])

def createTest[T](implicit tag: ClassTag[T]) = Test(Promise[T](), tag)

val seq: Seq[Test[_]] = Seq(createTest[String], createTest[Int])

seq.foreach { case Test(promise, tag) =>
  "asd" match {
    case tag(s) => promise.success(s)
    case _ => // nothing
  }
}

currently it yields the error:

found : s.type (with underlying type Any)

required: _$1 where type _$1





Scala, classTag and guice: Error injecting constructor, java.lang.StackOverflowError

In my play 2 application, I need to create a class tag in the class which is instantiated by guice (as eager singleton, this is requirement).

case class UserCreated(id: Long, userName: String) extends ApplicationEvent

@Singleton
class AccountRoleUpdater @Inject()
    (accountRepository: AccountRepository)
    (implicit val actorSystem: ActorSystem, ec: ExecutionContext) {

    implicit def ct: ClassTag[UserCreated] = classTag[UserCreated]

    // THIS LINE CAUSES ERROR       
    val cls = ct.runtimeClass.asInstanceOf[Class[UserCreated]]     
}

Here is guice bindning:

class Module extends AbstractModule with AkkaGuiceSupport {
    bind(classOf[account.eventlistener.AccountRoleUpdater]).asEagerSingleton()
}

When application starts, I'm getting exception:

CreationException: Unable to create injector, see the following errors:

1) Error injecting constructor, java.lang.StackOverflowError at account.eventlistener.AccountRoleUpdater.(AccountRoleUpdater.scala:45) at Module.configure(Module.scala:64) (via modules: com.google.inject.util.Modules$OverrideModule -> Module) while locating account.eventlistener.AccountRoleUpdater

1 error] at play.core.server.DevServerStart$$anon$1.reload(DevServerStart.scala:186) at play.core.server.DevServerStart$$anon$1.get(DevServerStart.scala:124) at play.core.server.AkkaHttpServer.modelConversion(AkkaHttpServer.scala:183) at play.core.server.AkkaHttpServer.handleRequest(AkkaHttpServer.scala:189) at play.core.server.AkkaHttpServer.$anonfun$createServerBinding$3(AkkaHttpServer.scala:106) at akka.stream.impl.fusing.MapAsync$$anon$23.onPush(Ops.scala:1172) at akka.stream.impl.fusing.GraphInterpreter.processPush(GraphInterpreter.scala:499) at akka.stream.impl.fusing.GraphInterpreter.processEvent(GraphInterpreter.scala:462) at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:368) at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:571) Caused by: com.google.inject.CreationException: Unable to create injector, see the following errors:

1) Error injecting constructor, java.lang.StackOverflowError at account.eventlistener.AccountRoleUpdater.(AccountRoleUpdater.scala:45) at Module.configure(Module.scala:64) (via modules: com.google.inject.util.Modules$OverrideModule -> Module) while locating account.eventlistener.AccountRoleUpdater

1 error at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:470) at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:184) at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110) at com.google.inject.Guice.createInjector(Guice.java:99) at com.google.inject.Guice.createInjector(Guice.java:84) at play.api.inject.guice.GuiceBuilder.injector(GuiceInjectorBuilder.scala:185) at play.api.inject.guice.GuiceApplicationBuilder.build(GuiceApplicationBuilder.scala:137) at play.api.inject.guice.GuiceApplicationLoader.load(GuiceApplicationLoader.scala:21) at play.core.server.DevServerStart$$anon$1.$anonfun$reload$3(DevServerStart.scala:174) at play.utils.Threads$.withContextClassLoader(Threads.scala:21) Caused by: java.lang.StackOverflowError: null at account.eventlistener.AccountRoleUpdater.ct(AccountRoleUpdater.scala:21) at account.eventlistener.AccountRoleUpdater.ct(AccountRoleUpdater.scala:21) at account.eventlistener.AccountRoleUpdater.ct(AccountRoleUpdater.scala:21) at account.eventlistener.AccountRoleUpdater.ct(AccountRoleUpdater.scala:21) at account.eventlistener.AccountRoleUpdater.ct(AccountRoleUpdater.scala:21) at account.eventlistener.AccountRoleUpdater.ct(AccountRoleUpdater.scala:21) at account.eventlistener.AccountRoleUpdater.ct(AccountRoleUpdater.scala:21) at account.eventlistener.AccountRoleUpdater.ct(AccountRoleUpdater.scala:21) at account.eventlistener.AccountRoleUpdater.ct(AccountRoleUpdater.scala:21) at account.eventlistener.AccountRoleUpdater.ct(AccountRoleUpdater.scala:21)

Seems some cycle reference...

Plese help!





Have not been able thus far to get Flask-MySQL reflection working

I've been searching StackOverflow questions and reading SQLAlchemy and Flask-SQLAlchemy docs, and have still not figured out how to get reflection working (still new to SQLAlchemy).

When I try to map the table using the engine, I get the error "sqlalchemy.exc.ArgumentError: Mapper Mapper|User|user could not assemble any primary key columns for mapped table 'user'". In spite of that, user has column 'id' as a primary key in the database. I'm not sure if there's something else I need to do here first. I had thought that if I could reflect, it would automatically give my User model class properties named after the database columns, and I wouldn't have to define them manually.

Here is my code that I've cobbled together so far:

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import mapper

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://" + dbUser + ":" + dbPass + "@" + dbAddress + ":3306/" + dbName

app.config["SQLALCHEMY_ECHO"] = True

db = SQLAlchemy(app)
engine = db.engine
meta = db.metadata

Now with that, I know that db will give me a good database session. I'm not sure yet about what I'm doing wrong with engine and meta. I've seen engine being used to create the context differently, but I think I'm creating that with this line (from above):

db = SQLAlchemy(app)

Here's the place where I'm trying to reflect a model class: class User(db.Model): try: self = db.Model.metadata.tables('user', metadata) #self = Tadb.Model.metadata.tables('user', meta, autoload=True, autoload_with=engine, extend_existing=True) #Table('user', metadata, autoload_with=engine, extend_existing=True) #self = Table('user', meta, autoload_with=engine, extend_existing=True) #self.metadata.reflect(extend_existing=True, only=['user']) except Exception as e: print("In init User(): failed to map table user - " + str(e))

I get the mapper error on this line (from above): self = db.Model.metadata.tables('user', metadata) I've tried the other lines as well, but it doesn't seem to know what Table is...I have Flask-SQLAlchemy 2.3.2.

Am I making any obvious mistakes here?





How to use reflection to link a const string field from one class to a readonly object field in another class

I have a class containing string constants and a class containing readonly objects representing a counter object. I have created a custom attribute that tags the string constant with the string representation of it's corresponding counter. Is there a good way to link the string const to the counter object using the attribute?

Here is an example of the string const:

public static class OperatorDiagnosticsConstants
{
  [CounterType(CounterType = "ReagentProbe1")]
  public const string R1_PROBE_CODE = "SACT-158";
}

Here is the class containing the readonly counter objects:

public class MaintenanceCounterType : CounterTypeEnum
{
    public static readonly MaintenanceCounterType ReagentProbe1 = new MaintenanceCounterType(MaintenanceCounterTypeConstants.ReagentProbe1ID);
}

I can think of two solutions but wonder if there is a more elegant way? First is in the code that uses these two classes, I could have a convert method with a switch statement. Switch on the attribute string to return the MaintenanceCounterType

public MaintenanceCounterType Convert(string attributeStr)
{
   switch (attributeStr)
   {
      case "ReagentProbe1":
        return MaintenanceCounterType.ReagentProbe1;
      ......
   }
  }

Or I think I could add the same custom attribute CounterType to the MaintenanceCounterType and use reflection to match them up. I guess by checking the equality of the string property of the custom attribute?

Looking for a more elegant solution. Thanks!





change the values of list in c# based on the certain value

I have the below mentioned list result which contains the volume for Eastern Day Light time and i want have latestResult list volume data for Mountain Standard Time

Can anyone please suggest optimized code to update the list values

var result = new List<XYZ>();
var latestResult = new List<XYZ>();

for(j=1;j<latestResult.count;j++)
for (i= diffvol;i< result.count; i++)
{
   //Code to implement

}
}

  public class XYZ
{
  public Decimal? B1Volume { get; set; }
  public Decimal? B2Volume { get; set; }
  public Decimal? B3Volume { get; set; }
public Decimal? B4Volume { get; set; }
  public Decimal? B5Volume { get; set; }
  .............
  .............
 public Decimal? B24Volume { get; set; }
}

I am trying to assign the value based on the timezone difference, Let's assume the timezone difference is 3 hours, I am assigning diffvol variable to 3 in the code

If the diffvol is 3 in the first iteration the following values need to be assigned to the list items

latestResult[0].B1Volume =  result[0].B3Volume;
latestResult[0].B2Volume =  result[0].B4Volume; 
latestResult[0].B3Volume = result[0].B5Volume;
...............
.................
latestResult[0].B21Volume = result[0].B24Volume;





Scala reflection. Get private field in trait

I am trying to use private trait field in testing. Very simple example:

//Works fine with class A, but not trait A
trait A {  
  private val foo = "Some string"
}

class Test extends A {
  val field = classOf[A].getDeclaredField("foo")
  field.setAccessible(true)
  val str = field.get(this).asInstanceOf[String]
}

I got:

java.lang.NoSuchFieldException: foo at java.lang.Class.getDeclaredField

live example here

How to get this snippet executable?





lundi 30 octobre 2017

Is there a way to assign a String object as a custom class instance?

Tried to extend from String class but it is final, hence looking for a way so that I can assign a String object as my custom class instance?

Example:

public class MyClass {
    public CustomString cString;
}

MyClass myClass = new MyClass();
Field field = myClass.getField("cString");
field.set(myClass, "TestValue");





Mapping all properties in one object to others by using expression trees instead of reflection in C#

How would we achieve mapping all properties in one object to others by using expression trees instead of reflection? what would be the alternatives for the following snippet?

 public class Mapper<TSource, TDestination> where TDestination : new()
{
    protected virtual void CopyMatchingProperties(TSource source, TDestination destination)
    {
        foreach (var destProp in typeof(TDestination).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanWrite))
        {
            var sourceProp = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                            .Where(p => p.Name == destProp.Name && p.PropertyType == destProp.PropertyType).FirstOrDefault();
            if (sourceProp != null)
            {
                destProp.SetValue(destination, sourceProp.GetValue(source, null), null);
            }
        }
    }

    public virtual TDestination MapObject(TSource source, TDestination destination)
    {
        CopyMatchingProperties(source, destination);
        return destination;
    }

    public virtual TDestination CreateMappedObject(TSource source)
    {
        TDestination destination = new TDestination();
        return MapObject(source, destination);
    }
}





Java: How can I instantiate a parent object from child without using parent constructor?

Here's the example:

public class Car{
  private float param;
  public Car(float rawParam) {
    // process rawParam before assign it to this.param
    this.param = rawParam * 2;
  }
}

public class Truck extends Car{
  public Truck(Car car) {
    // How do I instantiate Car?
  }
}

There's no default constructor, so I can't just create some arbitrary parent object then clone the passed car by reflection. The only constructor provided needs some raw params which are unknown to the parent object itself. How can I instantiate Car and Truck in this case? Thanks!





How can I add a class to Scala Set

I would like to passing a parameter via String and construct a Set of class objects, like this:

def getTypes(value: String) : Set[Class[Base]] = {
  var set = Set[Class[Base]]()
  var input = value.split(",")
  if(input.contains("XXX"))
    set ++ Class[xxx]
  if(input.contains("YYY"))
    set ++ Class[yyy]
  if(input.contains("ZZZ"))
    set ++ Class[zzz]
  set
}

Then looping the set and use class.newInstance() to create the actual object to do something later. The able code can compile, but when it run, it complaint that

Error:(32, 16) object java.lang.Class is not a value
    set ++ Class[xxx]

Any clue about about that?





Is it possible to programmatically get the number of times that a certain class was used in project?

Can you programmatically get the number of times that a certain class was used in the solution? Or simply a code for Find all References





dimanche 29 octobre 2017

Class member type check using reflection

I am trying to test the type of members in class. I am finding difficulty in testing type in the following code snippet.

What should be written in the place of ??? so that the result comes true?

Class Foo {
   private Integer a;
   private Byte[] b;
}

Class FooMain {
   public static void main(String[] args) {
      Fields f = Foo.class.getDeclaredFields();
      syso(f[0].getType() == Integer.class);
      syso(F[1].getType() == ????);
   }
}





Java Squiggly Line (~) Meaning? [duplicate]

This question already has an answer here:

In another stack overflow post, I saw some Java code like this, related to reflection:

public void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); }

I noticed that there is a squiggly line "~" in front of Modifier.FINAL. What is this "~"? I've never seen it before in Java code. I copied and pasted the code into Eclipse and it compiles so it's valid code.

Thank you in advance.





Invoking a arbitrary function/method

Lets say that I have a need to hold an arbitrary function f within a Node

case class Node[A](f: Any -> Any)

(I couldn't find any type around Function or Callable. Scala core just defines FunctionNs)

This node will then randomly sample arguments from a Terminal Set which it is going to use to call f.

So it needs to know two things:

  • the arity of f
  • how to invoke f

Additional:

I can retrieve the arity of a method object using

def arity(f: AnyRef): Option[Int] = {
  val apply = f.getClass.getMethods.find(_.getName == "apply")
  apply.map(_.getParameterCount)
}


def add(x: Int, y: Int) = {
  x + y
}

arity(add _)

However calling arity(f _) (within a Node instance) no longer works.

Besides this, I still have the problem of how to invoke f

If you have suggestions for an alternative design approach please let me know.





Kotlin - Is here a smart way to throw NotImplementedError for all the methods of a class?

I need to implement an interface (ResultSet) having hundreds of methods. For now, I'm going to implement only a subset of these methods, throwing a NotImplementedError for the others.

In Java I found two solutions:

  1. Create an abstract class AbstractResultSet implementing ResultSet, declaring all methods to throw NotImplementedError. No hacks, but a lot of boilerplate code.
  2. Use Proxy.newProxyInstance to implement all methods together in the InvocationHandler. Less code but also less immediate to use for other coders.

Is there a third option in Kotlin?

In my case, I need to implement a a ResultSet over an IBM dataset (with packed decimals, binary fields, zoned numbers, rows with variable length, etc.) to import it in a SQLServer via SQLServerBulkCopy. I don't know which ResultSet methods are called by this class, so, for now, I'm going to implement only the "most used" methods, logging the calls to unimplemented method.





Code generator for Android layout files

Is there any library that could help in generating XML (layout) files in android. I have explored java poet but it is not helping in XML files.





samedi 28 octobre 2017

c# Activator.CreateInstace how do i cast to generic base type?

I'm attempting to build a deck of cards (there are many different types of decks of cards) using generics based on derived types for suit, color, rank. I'm having an issue in how to create them using reflection and then cast the resulting object to the base PlayingCard type PlayingCard

    public class Name {}
    public class SpadesName : Name {}

    public class Color {}
    public class BlackColor : Color {}

    public class Rank {}
    public class AceRank : Rank {}

    public class PlayingCard<TName, TColor, TRank>
     where TName: Name, new()
     where TColor: Color, new()
     where TRank: Rank, new()
    {}

    public class DeckOfCards
    {
    public PlayingCard<Name, Color, Rank>[] cards;

    public DeckOfCards() {}

    public void BuildDeckOfCards()
    {
        this.cards = new PlayingCard<Name, Color, Rank>[52];

        Type[] fpcTypeArgs = { typeof(SpadesName), typeof(BlackColor), typeof(AceRank) };
        Type fpcType = typeof(PlayingCard<,,>);
        Type constructable = fpcType.MakeGenericType(fpcTypeArgs);

        // the problem is here.. this will not cast.
        // how do I create an object using reflection and cast it to the generic base type type PlayingCard<Name, Color, Rank>
        var fpc = Activator.CreateInstance(constructable);
        this.cards[0] = fpc; 
    }
 }





ClassNotFound Exception in Reflection created by Class name

I am facing difficulty with the below code. I need to create object through reflection by class name in Java but it throws below error while compiling.

// Class where package name with class is coming

public class PickAdapter<T> {


    Object mObject;

    public T read(Element element, String classOfName) {

        try {

            Class mClass = Class.forName(classOfName);


           mObject = mClass.newInstance();



            Field[] fd = mClass.getDeclaredFields();

 } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }


        return (T) mObject;

    }

// Error in Logcat

 10-28 17:12:54.619 20743-20743/com.harpz.htmlee D/NetworkSecurityConfig: No Network Security Config specified, using platform default
    10-28 17:12:55.771 20743-20743/com.harpz.htmlee W/System.err: java.lang.ClassNotFoundException: Invalid name: class com.harpz.htmlee.model.MUser
    10-28 17:12:55.771 20743-20743/com.harpz.htmlee W/System.err:     at java.lang.Class.classForName(Native Method)
    10-28 17:12:55.771 20743-20743/com.harpz.htmlee W/System.err:     at java.lang.Class.forName(Class.java:400)
    10-28 17:12:55.771 20743-20743/com.harpz.htmlee W/System.err:     at java.lang.Class.forName(Class.java:326)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at com.harpz.htmleetim.reflection.PickAdapter.read(PickAdapter.java:22)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at com.harpz.htmleetim.Htmlee.fromHtml(Htmlee.java:25)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at com.harpz.htmleetim.Htmlee.fromHtml(Htmlee.java:19)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at com.harpz.htmleetim.Htmlee.fromHtml(Htmlee.java:13)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at com.harpz.htmlee.MainActivity.onCreate(MainActivity.java:40)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at android.app.Activity.performCreate(Activity.java:6679)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at android.app.ActivityThread.-wrap12(ActivityThread.java)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at android.os.Looper.loop(Looper.java:154)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6119)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    10-28 17:12:55.772 20743-20743/com.harpz.htmlee W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)





How to InvokeMember with OptionalParamBinding and named parameters?

If I have a method which has optional arguments as follows:

public void foo(string argA, string argB = "", string argC = "")
{
   /* ... */
}

I can invoke this function without passing the optional argC using code such as:

Type _T = // get type;

dynamic instance = Activator.CreateInstance(_T);

_T.InvokeMember("foo",
                BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding,
                null,
                instance,
                new object[] { "A", "B"},
                null,
                null,
                new string[] { "argA", "argB" });

However, if I only want to pass argA and argC, omitting the optional argB, this fails with "System.IndexOutOfRangeException: Index was outside the bounds of the array."

_T.InvokeMember("foo",
                BindingFlags.InvokeMethod | BindingFlags.OptionalParamBinding,
                null,
                instance,
                new object[] { "A", "C"},
                null,
                null,
                new string[] { "argA", "argC" });

I realise I could work out the missing argument names but that would first entail establishing the most specific member (via call to _T.GetMember) effectively replicating what would have been done if it was a direct call rather than via reflection.

But, is there a way of doing this directly on the InvokeMember call?

For background, the actual code I'm working on is within the TryInvokeMember of a System.Dynamic.DynamicObject based class which itself has been called passing only argA and argC.

Thanks.





vendredi 27 octobre 2017

Use different Classes in a method

I have different Model classes which I will use with a master class. Every Model class have the same method "Change", but specific properties. The properties can be called by reflection.

Now I want to use every class with a generic string, because the model to use is stored in a database.

This is the working non generic code:

var inter = default(DDS.Model.Classname);
inter = new Master().DoSomeWhat<DDS.Model.Classname>(variableA)

Now I want to write the Classname generic like that:

Type stringClass = Type.GetType("DDS.Model.Classname");
var inter = default(stringClass);
inter = new Master().DoSomeWhat<stringClass>(variableA)

The error I got is "stringClass is variable, but is used like type" What can I do here?

Thank you in advanced. Nu





Populate object fields from another instance of the same class

I have two instances of the same class: one has values in all its fields and the other just some fields (the other fields are null). I want to update the values of the first object using the second's values, only if it isn't null. Something like this:

class MyObject {
    private void setObject(MyObject other) {
        if (other.getField1() != null) this.field1 = other.getField1();
        .....                
    }
}

The setObject method's code is really long when I have a lot of fields, and I need to implement that method in all my objects. I was wondering if it can be done on a more generic way: get object as argument -> iterate over its fields -> populate if isn't null.

I tried usage of some reflection to do this, unsuccessfully for now.





How to invoke with reflection a Java function which has method reference as parameters

A class (from Elasticsearch Rest API) has a protected method that I want to invoke. The problem is that this method has method reference parameters :

protected <Req extends ActionRequest, Resp> Resp performRequestAndParseEntity(
            Req request,
            CheckedFunction<Req, Request, IOException> requestConverter,
            CheckedFunction<XContentParser, Resp, IOException> entityParser,
            Set<Integer> ignores, Header... headers) throws IOException {
    return performRequest(request, requestConverter, (response) ->
        parseEntity(response.getEntity(), entityParser), ignores, headers);
}

In the API, this method is called that way:

DeleteIndexResponse deleteIndexResponse = restHighLevelClient.performRequestAndParseEntity(
    deleteIndexRequest,
    Request::deleteIndex,
    DeleteIndexResponse::fromXContent,
    Collections.emptySet(),
    headers
);

Java tells me that "The target type of this expression must be a functional interface" for DeleteIndexRequest::deleteIndex and DeleteIndexResponse::fromXContent

My (not working) solution:

java.lang.Class clazz = restHighLevelClient.getClass();
java.lang.reflect.Method performRequestAndParseEntity = clazz.getDeclaredMethod(
    "performRequestAndParseEntity",
    Object.class,
    org.elasticsearch.common.CheckedFunction.class,
    org.elasticsearch.common.CheckedFunction.class,
    java.util.Set.class,
    org.apache.http.Header.class
);
performRequestAndParseEntity.setAccessible(true);

org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse 
deleteIndexResponse = (org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse)
    performRequestAndParseEntity.invoke(
        restHighLevelClient,
        deleteByIndexRequest,
        org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest::deleteIndex,
        org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse::fromXContent,
        java.util.Collections.emptySet(),
        null
    )
;





How to get all objects from WINDOW (added from another classes)

I am working with specific program. It has "main window" (a.k.a. "form") where another extensions(protected dll, without access to their source code) can add some objects (texts, labels and etc..) in that window.

How can I access all the objects which is added on that "form" ?

here i example of typical extension:

....
namespace ProgramName.Extensions {

    public class MyExtensionName : ProgramName.ExtensionBase{

         //here goes typical codes to add things to "form" window,like:
         Draw.Arrow(MainFormObject, ArrowColor, ArrowWidth)

    }

}

what code I can use to access all "add"-ed elements , from other, anonymous/inaccessible classed? Is there any "reflection" or any solution?





Invoke Methods of abstract Types

I'm currently working on reflection with c# and I have a question. I try to invoke different class types which might be abstract or interface. So I just don't invoke the methods of those, because I cannot create an instance(obviously). But I'm not satisfied with this.


My question is: is it possible to work around this somehow and create an instance of something, where I can invoke the methods of the given abstract class type? Sorta like making a class that inherits from a Template which then can be the abstract type?

    foreach (MethodInfo m in _classType.GetMethods(bindingFlags))
    {
              if (_classType.IsAbstract || _classType.IsInterface)
              {
                   // only invoke instanciable types
                   MessageBox.Show("Abstract class and Interface cannot be invoked!");
              }
              else
              {
                   var ms = CreateStringFromMethodForCheckedBox(m);
                   if (s == ms)
                   {
                       m.Invoke(Activator.CreateInstance(_classType), null);
                   }
              }
     }





jeudi 26 octobre 2017

Object returned from FieldInfo.GetValue cannot be cast to Array

I'm working in a PCL (Profile7), and I've got an issue where the object returned from fieldInfo.GetValue(myItem) cannot be cast to an array.

I get a cast exception on a direct cast and (obviously) null when using As

enter image description here

how do I cast this object to a collection?

note: I have no idea what the type is as I don't have access to it. It's internal to the library I'm consuming





Scala reflection: Why does getMethods return private vals defined in superclass?

Code below defines a trait T with a private val someVal and an anonymous class extending T. If we call getMethods from the instance of the anonymous class, someVal is listed as a public method:

scala> trait T { private val someVal = 3 }
defined trait T

scala> new T {}.getClass.getMethods.apply(0)
res2: java.lang.reflect.Method = public int $anon$1.$line6$$read$T$$someVal()

Of course someVal isn't accessible in this subclass, but why is it even in the return of getMethods, as public?





Unable to load library using ReflectionOnlyLoadFrom

Well... I ´m having a problem with an 3rd party application that needs to connect to an Oracle Database. The problem is that 'Oracle.DataAccess' library is not being able to load.

The manufacturer told me to run the following command in powershell:

$path="D:\oracle\product\11.2.0\client_1\odp.net\bin\4\Oracle.DataAccess.dll"
[Reflection.Assembly]::ReflectionOnlyLoadFrom($path).ImageRuntimeVersion

And that is supposed to return the framework version that is being used. That does not work and throws the following message:

Exception calling "ReflectionOnlyLoadFrom" with "1" argument(s): "Could not loa d file or assembly 'http://file/D:\oracle\product\11.2.0\client_1\odp.net\bin\4\Ora cle.DataAccess.dll' or one of its dependencies. This assembly is built by a run time newer than the currently loaded runtime and cannot be loaded." At line:1 char:46
+ [Reflection.Assembly]::ReflectionOnlyLoadFrom <<<< ($path).ImageRuntimeVersio n
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

This server is running W2008 Server R2. The weird thing is that on another machine I have running W2012 Server the thing works just fine. I´ve already installed and repair all possible .net framework versions.

Can someone help me on this one?.





Create a list of all classes in namespace using reflection and cast to their real type

I have an abstract class Device. A number of classes derive from it, which represent specific devices. So we have, e.g. class RedDevice : Device, class BlueDevice : Device, etc. They are all stored under the Foo.Devices namespace. Here's an overview of the structure:

- Foo
|  ↳ Devices (folder)
|  |   ↳ RedDevice
|  |   ↳ BlueDevice
|  ↳ Device

I want to read create a list with all devices under Foo.Devices, cast to their parent class Device. I can get a list of Types using the following code:

List<System.Type> deviceTypes = 
    Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == 
    typeof(RedDevice).Namespace).ToList();

But how can I cast them to Device? Direct cast isn't allowed by the compiler and everything else throws wrong type exceptions. Thanks!





How can I get the string of a type in JavaScript/TypeScript?

In C# you could do something like this :

string typeName = typeof(int).FullName;

And the value of typeName would be System.Int32. (Refer this question for reference).

So, my question is, how can I achieve the same thing in JavaScript or TypeScript?

Please note that I do not want to get the type name from an object, I only want to get it from a type just like the example code above.





How to get the value of a private static field of a class from another OSGi bundle?

I'm inside MyBundle and I'd like to get the value of a static field LOGGER from AnotherClass defined in the following way inside AnotherBundle:

package org.example.anotherbundle.anotherpackage

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class AnotherClass {
    private static final Logger LOGGER = LoggerFactory.getLogger(AnotherClass.class);
    ...
}

I tried doing it like this:

import org.osgi.framework.Bundle;
import org.eclipse.core.runtime.Platform;
import java.lang.reflect.Field;
import org.example.anotherbundle.anotherpackage.AnotherClass;

...

Bundle bundle = Platform.getBundle("org.example.anotherbundle");
Class<?> clazz = bundle.loadClass(AnotherClass.class.getName());
Field logger_field = clazz.getDeclaredField("LOGGER");
Object logger = logger_field.get(null); <-- NullPointerException is thrown here, but why??

I'm wondering why the NullPointerException is thrown by the get(Object object) method in the last line. The java.lang.reflect.Field documentation says that this exception is thrown only when the specified object is null and the field is an instance field. But in this case it is a static field, so it's OK to pass null to that method because it should ignore this argument anyway, right?





Disabling the functions in a string c#

I know that we can call functions with their name stored in a string like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

Is their any way in C# by which I can call all the functions in the class except the function in a string?

Want it in late binding, as I have array of strings which includes the methods name which needs to be discarded from the execution.





How to describe an expected play-json Reads format programmatically

I have many case classes that defines json Read/Write/Format using play-json library. Typical example of such a definition is done using macro

case class Payload(
                    file: FilePayLoad,
                    comment: String
                  )

object Payload {
  implicit val format: Format[Payload] = Json.format[Payload]
}

No trouble for writing more specific formats or anything else using the library apis.

Is there any possibility to perform reflection or type analysis on the OReads implicit defined ? I now little about type level programming, and enough about implicits to retrieve the implicits generated by the macro expansion but I'm working on a self discoverable REST api and I would need to print out the expected JSON format for a given payload case class

Is there any way to reverse the play-json reads definition to print something like this

 "format": {
    "/payload": {
        "/file": {
            "type": "FilePayLoad"
            "format": {
                "/name": {
                    "type": "String",
                    "optional": false
                },
                "/mimeType": {
                    "type": "String",
                    "optional": false
                },
                "/filesize": {
                    "type": "Double",
                    "optional": false
                },
            },
        },
        "/comment": {
            "type": String,
            "optional": false
        }
    }
 }





mercredi 25 octobre 2017

What is wrong with paths in loader.setLocation in FXMLLoader?

I am learning JavaFX with this tutorial

My Code:

package ch.makery.address;

import java.io.IOException;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class MainApp extends Application {

    private Stage primaryStage;
    private BorderPane rootLayout;

    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("AddressApp");

        initRootLayout();

        showPersonOverview();
    }

    /**
     * Initializes the root layout.
     */
    public void initRootLayout() {
        try {
            // Load root layout from fxml file.
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainApp.class.getResource("view/RootLayoutInner.fxml"));
            rootLayout = (BorderPane) loader.load();

            // Show the scene containing the root layout.
            Scene scene = new Scene(rootLayout);
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Shows the person overview inside the root layout.
     */
    public void showPersonOverview() {
        try {
            // Load person overview.
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(MainApp.class.getResource("PersonOverview.fxml"));
            AnchorPane personOverview = (AnchorPane) loader.load();

            // Set person overview into the center of root layout.
            rootLayout.setCenter(personOverview);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Returns the main stage.
     * @return
     */
    public Stage getPrimaryStage() {
        return primaryStage;
    }

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

When I'm trying to load fxml according to author:

FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/RootLayoutInner.fxml"));
rootLayout = (BorderPane) loader.load();

I get such exception:

    Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Location is not set.
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2434)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
    at ch.makery.address.MainApp.initRootLayout(MainApp.java:35)
    at ch.makery.address.MainApp.start(MainApp.java:22)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    ... 1 more
Exception running application ch.makery.address.MainApp

Process finished with exit code 1

When I move RootLayout.fxml and PersonOverview.fxml to the same folder where MainApp.java exists everything is ok:

FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();

So, can anyone help me understand how to handle with paths and loader?





Overriding method level @annotation at runtime with reflection, works for class level

Problem: I am able to successfully override class level annotations using the following:

public static void alterClassAnnotation(Class classToLookFor, Class<? extends Annotation> annotationToAlter,Annotation annotationValue) {
        if (isJDK7OrLower()) {
            try {
                Field annotations = Class.class.getDeclaredField(ANNOTATIONS);
                annotations.setAccessible(true);
                Map<Class<? extends Annotation>, Annotation> map =
                    (Map<Class<? extends Annotation>, Annotation>) annotations.get(classToLookFor);
                map.put(annotationToAlter, annotationValue);
            } catch (Exception  e) {
                e.printStackTrace();
            }
        } else {
            try {
                //In JDK8 Class has a private method called annotationData().
                //We first need to invoke it to obtain a reference to AnnotationData class which is a private class
                Method method = Class.class.getDeclaredMethod(ANNOTATION_DATA, null);
                method.setAccessible(true);
                //Since AnnotationData is a private class we cannot create a direct reference to it. We will have to
                //manage with just Object
                Object annotationData = method.invoke(classToLookFor);
                //We now look for the map called "annotations" within AnnotationData object.
                Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS);
                annotations.setAccessible(true);
                Map<Class<? extends Annotation>, Annotation> map =
                    (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData);
                map.put(annotationToAlter, annotationValue);
            } catch (Exception  e) {
                e.printStackTrace();
            }
        }
    }

I am confused with the reflection API, how can I modify this code in order to override the value of a method level paramater? I have 3 annotations, 2 of which can be set at class level so I'm overriding them successfully with this code, but how about if the annotation is against the method itself?

my implementation class of the interface:

import java.lang.annotation.Annotation;

import io.qameta.allure.junit4.DisplayName;
public class DynamicDisplayName implements DisplayName {

    private String value;

    public DynamicDisplayName(String value) {
        this.value = value;
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @Override
    public String value() {
        return value;
    }

}

I have successfully overridden Issue and TmsLink, here is my code (both of these interfaces function correctly at class level)

Issue issue = SaveCourse.class.getAnnotation(Issue.class);
DynamicIssue altered = new DynamicIssue(issueId);
AnnotationHelper.alterClassAnnotation(SaveCourse.class, Issue.class, altered);
issue = SaveCourse.class.getAnnotation(Issue.class);                 


DisplayName dname = SaveCourse.class.getAnnotation(DisplayName.class);
DynamicDisplayName dna = new DynamicDisplayName(displayName);
AnnotationHelper.alterClassAnnotation(SaveCourse.class, DisplayName.class, dna);
dname = SaveCourse.class.getAnnotation(DisplayName.class);

TmsLink tmslink = SaveCourse.class.getAnnotation(TmsLink.class);
DynamicTmsLink tmsaltered = new DynamicTmsLink(testCaseId);
AnnotationHelper.alterClassAnnotation(SaveCourse.class, TmsLink.class, tmsaltered);
tmslink = SaveCourse.class.getAnnotation(TmsLink.class);

The displayName interface:

/**
 * Used to change display name for test in the report.
 */
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface DisplayName {

    String value();

}





Obtain a property from all colors in Xamarin.Forms.Color

Let's say I want to obtain the"R" component from all Colors in Xamarin.Forms.Color. I tried this:

var RComponentList = typeof(Color).GetRuntimeFields(). Select((f) => f.GetType().GetRuntimeProperty("R"));

but the result is a list of nulls. Is like it managed to find the colors but not the "R" property in each of them. How can I achieve this ?. Thank you.





Appending to a slice using reflection

I would like to append to a slice using only reflection. But I can't figure out how to "replace" the value of a with the new slice.

func main() {
    fmt.Println("Hello, playground")

    a := []string {"a","b","c"}

    values := []string {"d","e"}

    v := reflect.ValueOf(a)

    fmt.Printf("%t\n\n", v.Type())
    fmt.Printf("%t\n\n", v.Type().Elem().Kind())

    for _, val := range values {
        v.Set(reflect.Append(v, reflect.ValueOf(val)))
    }

    fmt.Printf("%t - %v", a, a)
}

This code is available for fiddling at http://ift.tt/2z6fMDC.





Display all properties and if property is a class display its properties

I am using reflection to loop through classes of a DLL and display the properties of that class; but there are cases where the property is another class, and I need to loop through that property's properties and display them.

What I currently have will only display the properties, and not sub properties:

treeView1.Nodes.Clear();

Assembly assembly = Assembly.LoadFrom(@"Path\Domain.dll");

            int count = 0;
            foreach (Type type in assembly.GetTypes().Where(t => t.IsClass))
            {               
                var node = treeView1.Nodes.Add(type.FullName);

                var x = ((System.Reflection.TypeInfo)((assembly.GetTypes()))[count]).DeclaredProperties;

                x.ToList().ForEach(item => treeView1.Nodes[count].Nodes.Add(item.Name));

                count++;                
            }           
        }

Any help to display sub properties





C# dynamically set property using lambda? [duplicate]

This question already has an answer here:

I have a tree constructed using a TreeNode class where each node has an Amounts object. The Amounts object is a simple class that houses some decimal values. E.g.

public class Amounts
{
    public decimal Amount1 { get; set; }
    public decimal Amount2 { get; set; }
    ...
}

I need to be able to performsum up the individual properties independently, and what I'd like to do is somehow pass one of the Amounts properties to this method using a lambda or similar but I can't quite work out how to do this (I've been a while off the tools unfortunately). I don't particularly like the idea of passing a property name string so I can use reflection SetPropertyValue method.

The traversal method looks something like this (a little contrived of course):

public void Traverse()
{
    foreach (var child in this.Children)
    {
        this.Amounts.Amount1 += child.Amounts.Amount1;
    }            
}

Rather than having a separate method for each amount, I'd like to do be able to call it something like below:

Traverse(a => a.Amount1);

I'm not sure if I have explained the requirement very well, but hopefully enough to get a pointer in the right direction.

Thanks, John





Java Enums - ENUM$VALUES or $VALUES

How can I determine the logic used for naming the synthetic attribute created inside enums to store the values of it in Java?

I've been trying to find either documentation without luck, I also looked at the source to see if I was able to get some more insight on my own. So far the only thing I've been able to find is this post where apparently the conclusion indicates that the naming for it depends entirely on the compiler, nonetheless I've seen both namings on the same project on the same execution on different classes.

Can anybody shed some light onto how is this synthetic field gets named?

Or how can I determine/dictate if an enum would use the $VALUES or the ENUM$VALUES name? (Of course without testing it first through reflection)





mardi 24 octobre 2017

Generically set value of field on any struct

I would like to be able to create a function which can accept any struct as an argument and set the first field of that struct to a certain value (my actually use case is different but this was a minimal example which exhibited the problem).

Here is my attempt so far: go playground link

 package main

 import (
    "fmt"
    "reflect"
 )

 type A struct {
    X string
 }

 // this works
 func modifyFieldsForA(v A) interface{} {
    f := reflect.ValueOf(&v).Elem()
    f.Field(0).SetString("Modified")
    return f.Interface()
 }


 type B struct {
    Y string
    Z string
 }

 // this gives an error "reflect: call of reflect.Value.Field on interface Value"
 func modifyFieldsGeneric(v interface{}) interface{} {
    f := reflect.ValueOf(&v).Elem()
    f.Field(0).SetString("Modified")
    return f.Interface()
 }

 func main() {
    a := A{"hello"}
    a2 := modifyFieldsForA(a)
    fmt.Printf("New a: %+v\n", a2)
    a2 = modifyFieldsGeneric(a)
    fmt.Printf("New a: %+v\n", a2)

    b := B{"hello", "word"}
    b2 := modifyFieldsGeneric(b)
    fmt.Printf("New b: %+v", b2)
 }

The first function which acts only on structs of type A works fine. The second one does not. I think because the reflection library does not necessarily know I'm definitely going to give it a struct rather than an instance of any interface. Is there a way to get the generic function to work?

Thanks!





Groovy: Get the children of a class [duplicate]

Is there any way to get all the descendants names of a class?

The hierarchy of my class is something like this:

[ ParentClass ]

[ Battery extends ParentClass ]
[ Cover extends ParentClass ]
[ Dispense extends ParentClass ]
[ Known extends ParentClass ]
[ Product extends ParentClass ]

I'm doing something like that:

['Battery', 'Cover', 'Dispense', 'Known', 'Product'].each {
    def className = "com.package.${it}"
    ...
}

But if in a future we add a child I will need to add another element in the array.

And I shouldn't add this code in the domain, because is something that marshallize stuff.





Passing template parameters to Class#newInstance()

I have the following interface:

interface Processor<T> {
    void process( T request );
}

I then call the following:

Processor<String> p = Processor.class.newInstance();

Eclipse complains, as a warning against Processor.class.newInstance():

"Type safety: The expression of type Processor needs unchecked conversion to conform to Processor< String>"

How do I specify the template parameters to this expression? Something like:

Processor<String> p = Processor.class.newInstance<String>();





C# Reflection Method.Invoke NullReferenceException [duplicate]

This question already has an answer here:

I've been trying to familiarize myself with reflection as much as I can and have been trying to invoke a method in an instanced class from a static class(and method). I'm not having much luck and keep getting a nullreferenceexception.

Type clss = Type.GetType(reader.GetString());
Debug.Log(clss.Name);
string methodname = reader.GetString();
object instance = clss.GetField("inst", BindingFlags.Static | BindingFlags.Public).GetValue(null);  Debug.Log(instance.GetType().IsInstanceOfType(instance));

int x = reader.GetInt();
float y = reader.GetFloat();

Debug.Log(x);
Debug.Log(y);

Debug.Log(instance.GetType().GetMethod(methodname, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) == null);

instance.GetType().GetMethod(methodname, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Invoke(instance, new object[] { x, y });

I've done multiple checks. The class type exists, the instance object isn't null, x and y aren't null. None of the variables I'm using are null but as soon as I use invoke it throws a nullreference.

Debug.Log(instance.GetType().IsInstanceOfType(instance));

tells me that it is indeed an instance of the class I want so I'm at a loss.

If anyone could help me that would be great, thanks!





How do I convert a string into an executable line of code in objective-c

i know this question might be duplicate. i searched and tested a lot of code samples and librarys but still no good results.

the question is i want to do something like this in objective-c (ios): (its the idea , not the exact syntax)

NSString *Cmd=@" if (10>5) NSLog(@"Test");  ";
MyClass.Run(Cmd);

i expect that "Test" appear in Output Log.

after Researches, i Ended Up with these 2 libraries for compile in runtime:

1- libClang framework and clang_Cursor_Evaluate function .

http://ift.tt/1aSP7Dk

http://ift.tt/2yJIxCO

2-objc-eval framework .

http://ift.tt/2yOxmej

i could not do anything with libClang. and left it alone for now.

but with the secound one , i successfully compiled the framework and actualy used it in a simple project, however still no proper output!

#import <Foundation/Foundation.h>
#import "OEEvaluation.h"
void main()
{
Code1:OEEvaluation *evaluation = [OEEvaluation evaluationWithCode:@"retun @\"Hello World!\" ;" delegate:nil];
Code2://OEEvaluation *evaluation = [OEEvaluation evaluationWithCode:@"NSLog(@\"Hello World!\");" delegate:nil];
NSLog([evaluation evaluateSynchronously]);
NSLog(@"Test");
}

no output with Code1 and Code 2 . no (null) , no error, no hint.. nothing at all.

code 1 is the exact sample of the framework

maybe im wrong but i think the solutions i found are the closest Once to the answer between my researches.

now the questions are:

1- what is your suggestion to accomplish this idea (convert a string into an executable line of executable code)?

2-how to get the objc-eval.framework to work?

any tips,tuts, hints, link , sample code and guide will be appreciated. sorry for my bad english. thank you





Java reflection with Serve modules without publishing

I have a problem with reflection on Web Application using com.google.common.reflect.ClassPath. And see below for my sample code.

ClassLoader loader = Thread.currentThread().getContextClassLoader();
ImmutableSet<ClassInfo> classInfos = ClassPath.from(loader).getTopLevelClassesRecursive(PATH);

Basically getTopLevelClassesRecursive returns as I expected, but when using it with 'Serve modules without publishing', it returns nothing.

Reading from the questions below, I guess the cause of it is deference of the scope of WebAppClassLoader between using 'Serve modules without publishing' and not using it.

Technical details of serve modules without publishing in Eclipse WTP and Tomcat?

Dose anybody have an idea to solve this problem?





lundi 23 octobre 2017

.Net EF Dynamic CSV Import

I am building a CSV import library to import CSV with user defined mapping. How it will work is, user will be presented with UI to map CSV column with EF Table->Column (drag & drop or connecting lines between). Once this is done, library will import that CSV into the mapped tables.

Problem I have is, there will be about 40-50 tables (couple of tables with more than 40 columns) so I don't want to use switch or if. I will have string name of Table and column (using diff display name will be good but not required) with mapped csv column name (and index). From this, I want to import all the csv records. I also need to consider reference (foreign key) linking where CSV will contain foreign key value not id so I need to connect referenced table to get id.

I am think lambda expression with reflection may help but not sure how. I have looked at reply from Matt Searles but didn't quite understand how to use that and also don't know where's ToSeperatedString coming from. Also looked at CsvHelper but don't think that will be helpful when entity name is not known at design time.

Would appreciate any help. Thanks





Activator.CreateInstance gives MissingMethodException

I have this few lines:

private Type providerType; // this DOES get a value before using CreateNewProperty so it isn't null.

public IUniqueProperty CreateNewProperty(PropertyInfo propertyInfo, 
   Type containerClassType)
{
    var obj = (IUniqueProperty)Activator.CreateInstance(providerType); //this line gives the error.
    obj.ID = RequestID;
    obj.PropertyInfo = propertyInfo;
    obj.ContainerClassType = containerClassType;
    properties.Add(obj);
    return obj;
}

And the line I marked with a comment gives me the following error message:

MissingMethodException: Method not found: 'Default constructor not found...ctor() of Assets.Helper.UniquePropertyProvider'. System.Activator.CreateInstance (System.Type type, Boolean nonPublic) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Activator.cs:368) System.Activator.CreateInstance (System.Type type) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Activator.cs:254) Assets.Helper.PropertyFactory.CreateNewProperty (System.Reflection.PropertyInfo propertyInfo, System.Type containerClassType) (at Assets/Helper/PropertyFactory.cs:55) Assets.ViewModelBase.MatchProperty (Assets.Bindable b) (at Assets/ViewModelBase.cs:135) Assets.ViewModelBase.Connect (System.Collections.Generic.List`1 bindables) (at Assets/ViewModelBase.cs:172) Assets.ViewModelBase..ctor (Assets.View v) (at Assets/ViewModelBase.cs:24) Assets.Test.TestViewModel..ctor (Assets.View v) (at Assets/Test/TestViewModel.cs:11) Assets.Test.TestBL.Awake () (at Assets/Test/TestBL.cs:14)

Basically telling me it has found no constructor. The intention with this one is that I want to create an interface, so when instantiating the class this CreateNewProperty is in, I pass in a type that implements that interface and I want to instantiate a class of the given type I passed in, but eventually returning it as an interface. Question is, what is the problem?

edit

The method is called like

var newProp = propertyFactory.CreateNewProperty(p, item.GetType());

and the PropertyFactory in the making is instantiated like this:

propertyFactory = new PropertyFactory(typeof(UniquePropertyProvider));

And the type to instantiate:

public class UniquePropertyProvider : IUniqueProperty
{
    private int id;
    private PropertyInfo propertyInfo;

    public UniquePropertyProvider(int id, PropertyInfo propertyInfo)
    {
        this.id = id;
        this.propertyInfo = propertyInfo;
    }

    public int ID
    {
        get { return id; }
        set { id = value; }
    }

    public PropertyInfo PropertyInfo
    {
        get { return propertyInfo; }
        set { propertyInfo = value; }
    }

    public Type ContainerClassType { get; set; }
}





dimanche 22 octobre 2017

C# How would I get a field through reflection once and make a delegate that returns its value for future use?

My use case: In my game I have an overlay that tracks any field with the '[TrackedField]' attribute. I want it to display the name of the variable, and the current value. Reflection being a bit of an expensive operation, I was looking for a way to retrieve the value once through reflection, and then make a delegate function, which doesn't use reflection, that returns the field's value. That way it can be called whenever I want to update that value on the overlay.

I actually don't know if what I'm asking is even possible, or if there would be a better way to retrieve this value. I've searched around for the past couple days, but all I was able to dig up was this related post. It will most likely be updated multiple times a second, so I'd like to avoid repeated use of reflection if I can.

Currently my code just gets every variable name (or a label defined in the attribute) and displays it with a dummy delegate that just reads "error":

MonoBehaviour[] sceneActive = GameObject.FindObjectsOfType<MonoBehaviour>();

foreach (MonoBehaviour mono in sceneActive)
{
    System.Type monoType = mono.GetType();

    // Retreive the fields from the mono instance
    FieldInfo[] objectFields = monoType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

    // search all fields and find the attribute [TrackedField]
    for (int i = 0; i < objectFields.Length; i++)
    {
        TrackedFieldAttribute attribute = Attribute.GetCustomAttribute(objectFields[i], typeof(TrackedFieldAttribute)) as TrackedFieldAttribute;

        // if we detect any attribute add it to the overlay
        if (attribute != null)
        {
            trackerBar.AddTab(attribute.label == null ? objectFields[i].Name : attribute.label, () => { return "error"; },attribute.color);
        }
    }
}

Here's an example of the '[TrackedField]' attribute in action:

[TrackedField]
private bool consoleOpen = false;
[TrackedField("MyLabel")]
private bool overlayShown = false;
[TrackedField("ColoredLabel", 50, 50, 255)]

It results in this on the overlay, if you were curious.

And if you were interested in what the attribute looked like:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class TrackedFieldAttribute : Attribute
{
    private string _label;
    private Color _color;

    public TrackedFieldAttribute()
    {
        _label = null;
        _color = default(Color);
    }

    public TrackedFieldAttribute(string label)
    {
        _label = label;
        _color = default(Color);
    }

    public TrackedFieldAttribute(float red = 0, float green = 0, float blue = 0)
    {
        _label = null;
        _color = new Color(red / 255f, green / 255f, blue / 255f);
    }

    public TrackedFieldAttribute(string label, float red = 0, float green = 0, float blue = 0)
    {
        _label = label;
        _color = new Color(red / 255f, green / 255f, blue / 255f);
    }

    public string label
    {
        get { return _label; }
        set { _label = value; }
    }

    public Color color
    {
        get { return _color; }
        set { _color = value; }
    }
}





Getting a class's type after passing it as an ancestor class

I have some classes, for example

  • IntentoryItem, a base class for all items in inventory,
  • Weapon, all the weapons, derived from InventoryItem,
  • Shotgun, Rifle, Handgun etc and many more, all are Weapons.

I have this method:

private void SomeMethod(InventoryItem g)
{
    var myClasses = g.GetType().FindAllDerivedTypes<InventoryItem>();
    //do something with myClass
}

The problem is with FindAllDerivedTypes<InventoryItem>(). If I implement it the way like so:

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

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

(as found on another SO thread) I get all the classes that are derived from my InventoryItem, which is fine, but I need only those relevant to my case, so if a Shotgun was passed as an InventoryItem, I want to get a Shotgun, if I pass another one, I want to get it as another one. Question is, what am I doing wrong?

EDIT

The goal:

doesn't matter what InventoryItem I pass, I need to get the passed instance's type, and only that one type. say I call it like so:

Shotgun s = GetShotgunFromSomewhere();

SomeMethod(s);  //here `Shotgun` is an `InventoryItem`, and was passed like that.

However, inside that method I need the Shotgun class, and not an InventoryItem, and I can't cast it by hand like this:

var myVar = (Shotgun)g;

because I have a lot of inventory items and I would have to do all by hand.

g.GetType();

wasn't working out. Should it return a Shotgun or an InventoryItem? Because when using it, I expected a shotgun but got the inventory item.





Access Kotlin Delegate Type without an Instance

I have read Access property delegate in Kotlin which is about accessing a delegate from an instance. One can use KProperty::getDelegate since Kotlin 1.1, however this will return the instance of the delegate and therefore needs an instance of the class first.

Now I want to get the type of the delegate without having an instance of the class. Consider a library with a custom delegate type CustomDelegate that want's to get all properties of a class that are delegated to an instance of CustomDelegate:

class Example
{
    var nonDelegatedProperty = "I don't care about this property"
    var delegatedProperty1 by lazy { "I don't care about this too" }
    var delegatedProperty2 by CustomDelegate("I care about this one")
}

How can I, given I have KClass<Example>, but not an instance of Example, get all properties delegated to CustomDelegate?





samedi 21 octobre 2017

Reading data embedded into a .NET assembly

For a school project I'm not allowed to use stored procedures to store my SQL scripts.To solve this I tried to create a SQL_scripts folder inside my class assembly.

My project structure

Now I'm stuck on how to read my script from a relative path?

Here what I tried without success:

var appDomain = System.AppDomain.CurrentDomain;
                var basePath = appDomain.RelativeSearchPath ?? appDomain.BaseDirectory;
                string path = Path.Combine(basePath, "SQL_scriptes", "GetAllEmptyRoomsAtDateRange.sql");
                string query = File.ReadAllText(path);

But I'm always in the following folder:

  • MyProject\Tests\bin\Debug\SQL_scriptes\GetAllEmptyRoomsAtDateRange.sql

Any idea?





Create namedtuple instance from string on runtime (reflection /dynamic creation)

How can I create instance of a namedtuple dynamically? is it possible?

Msg = collections.namedtuple('Msg', 'a b c')
...
mymsg = Msg(a=1,b=2,c=3)
msg_as_dict = mymsg._as_dict()
msg['recover_name'] = type(mymsg).__name__

How can I create Msg instance back from msg['recover_name'] on runtime?





Getting a value from the class in a JAR file

I want to run a method in JAR, and the method will look like public static SomeType getValue().

I tried to use reflection and it seemed okay:

URLClassLoader classLoader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}, Main.class.getClassLoader());
Class targetClass = classLoader.loadClass("some.package.TargetClass");
Class targetType = classLoader.loadClass("some.package.SomeType");
Method getValueMethod = targetClass.getMethod("getValue");

But while getting a return value like this:

targetType value = targetClass.cast(getValueMethod.invoke(null));

value's type cannot be targetType, isn't it? However, the type SomeType is in the JAR file, so I can't do like SomeType value = ~~

Then, how can I get getValue()'s value properly and access its data?





How do I append to a slice field in a struct using reflection?

I have a struct that looks like this:

type guitaristT struct {
    Surname  string   `required=true`
    Year     int64    `required=false`
    American bool     // example of missing tag
    Rating   float32  `required=true`
    Styles   []string `required=true,minsize=1`
}

I have an environment variable that looks like the following, and I'm using reflection to fill the struct based on the keys.

jimiEnvvar :="surname=Hendrix|year=1942|american=true|rating=9.99
  |styles=blues|styles=rock|styles=psychedelic"

I'm able to set the string, int64, bool and float32 fields using reflection, but I'm stuck on how to append to the slice field Styles. For example, based on the above jimiEnvvar I would like the field jimi.Styles to have the values ["blues","rock", "psychedelic"].

I have the following (simplified) code:

result := guitaristT{}
result.Styles = make([]string, 10)
...
v := reflect.ValueOf(&result).Elem()
...
field := v.FieldByName(key) // eg key = "styles"
...
switch field.Kind() {

case reflect.Slice:
     // this is where I get stuck
     //
     // reflect.Append() has signature:
     //   func Append(s Value, x ...Value) Value

     // so I convert my value to a reflect.Value
     stringValue := reflect.ValueOf(value) // eg value = "blues"

     // but this doesn't append:
     field = reflect.Append(field, stringValue)


If you're interested, the full code is at http://ift.tt/2hUOEfA . It just some notes I'm writing for myself; crazy names I know :-)





How to load .class from working directory at runtime from jar?

Attempting to implement a plugin system for my application, the code of which extends my Plugin class to define custom functionality.

This code to load a class from within a jar, in the same directory as the .jar of the application, works fine:

if(pluginName.endsWith(".jar"))
{
    JarFile jarFile = new JarFile(pluginName);
    Enumeration jarComponents = jarFile.entries();

    while (jarComponents.hasMoreElements())
    {
        JarEntry entry = (JarEntry) jarComponents.nextElement();
        if(entry.getName().endsWith(".class"))
        {
            className = entry.getName();
        }
    }

    File file = new File(System.getProperty("user.dir")+"/"+pluginName);
    URLClassLoader loader = new URLClassLoader(new URL[]{file.toURI().toURL()});

    Class newClass = Class.forName(className.replace(".class", ""), true, loader);
    newPlugin = (Plugin) newClass.newInstance();
}

Which results in the correct response of:

benpalmer$ java -jar assignment.jar test_subproject.jar
- INFO: Add new plugin: source.com

The issue is I also want to provide the user the option to specify a .class file instead, as that is realistically all that is packed into a .jar for the purposes of my plugin system.

else if(pluginName.endsWith(".class"))
{
    File file = new File(System.getProperty("user.dir")+"/"+pluginName);
    URLClassLoader loader = new URLClassLoader(new URL[]{file.toURI().toURL()});

    Class newClass = Class.forName(className.replace(".class", ""), true, loader);
    newPlugin = (Plugin) newClass.newInstance();
}   
... exception handling

Which results in the following:

benpalmer$ java -jar assignment.jar TestPlugin.class
SEVERE: Error: Plugin class not found. Class name: 
java.lang.ClassNotFoundException: 
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at newsfeed.model.Plugin.loadClassFromJarFile(Plugin.java:144)
    at newsfeed.controller.NFWindowController.initPlugins(NFWindowController.java:81)
    at newsfeed.controller.NewsFeed$1.run(NewsFeed.java:20)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

I've tried the code above and many variations of path names/other options, but get ClassNotFoundException every time. Originally had trouble loading the jars but using the fully qualified path fixed that, now I can't load the Classes.

Any ideas? :)





VSIX: AppDomain CreateInstanceAndUnwrapError

I have created AppDomainSetup and applied to console project and it works fine. But when I applied it with VSIX, it doesn't work and I don't know why. Could you someone look into it and help me get out of it. Thanks in advance.

public class Proxy : MarshalByRefObject

{

    public Proxy()
    {

    }
    public Type[] GetTypes(string assemblyName)
    {
        var assembly = Assembly.LoadFile(assemblyName);
        return assembly.GetExportedTypes();
    }

}

The code on VSIX MenuItemCallback

    private void MenuItemCallback(object sender, EventArgs e)
    {
        string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
        string title = "ProxyCommand";

        var cachePath = Path.Combine(@"D:\Temp", "ShadowCopyCache");
        var pluginPath = Path.Combine(@"D:\Temp", "Plugins");
        if (!Directory.Exists(cachePath))
        {
            Directory.CreateDirectory(cachePath);
        }

        if (!Directory.Exists(pluginPath))
        {
            Directory.CreateDirectory(pluginPath);
        }
        var setup = new AppDomainSetup
        {
            CachePath = cachePath,
            ShadowCopyFiles = "true",
            ShadowCopyDirectories = pluginPath
        };

        domain = AppDomain.CreateDomain("MyDomain", AppDomain.CurrentDomain.Evidence, setup);

        domain = AppDomain.CreateDomain("MyDomain", AppDomain.CurrentDomain.Evidence, setup);
        var proxy = (Proxy)domain.CreateInstanceAndUnwrap(typeof(Proxy).Assembly.FullName, typeof(Proxy).FullName);
        var types = proxy.GetTypes("TestAssembly");           
        AppDomain.Unload(domain);
    }





vendredi 20 octobre 2017

How to get values of all nested fields given their names?

Say we have a class instance foo and foo.bar == 42 and foo.box.bar == 34 and there can be more bar's in there. How to gather all bar values from a class instance (and all nested within) as an array [42, 34]?





How to check if ReflectionProperty is accessible?

Is there a way to check that I've already set a ReflectionProperty to be accessible?

class Foo {
    private   $baz  = 'bar';
}

$foo = new Foo();

$prop = new ReflectionProperty($foo, 'baz');
$prop->setAccessible(true);

Doing $prop->isPrivate(); will return true before and after setting the accessibility (as expected). Is there a way to tell that I've already set the accessibility to true?

The documentation doesn't show anything like an $accessible property in the ReflectionProperty class, so I'm not sure how it's making it accessible, unless it's done on the Foo class.





getting properties using reflection

im using reflection for getting some properties, and im having problems getting one when the GetValue(item,null) returns an object. i did:

foreach (var item in items)
{
   item.GetType().GetProperty("Site").GetValue(item,null)
}

doing that, i got an object System.Data.Entity.DynamicProxies.Site. Debugging it, i can see all properties of that object, but i can`t get it. For example, one property is: siteName, how can i get the value of that? Thanks.





Why does loading the System assembly work in the F# Repl, but not in compiled code?

let system = System.Reflection.Assembly.Load("System")
()

This works for me in the Repl, but not when compiled. Any idea why?

On compiled, I get the following exception:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System' or one of its dependencies. The system cannot find the file specified.





How to change a member field with Kotlin reflection?

I'm porting a class from Java to Kotlin. This class declares hundreds of objects. Each object has a name property which is identical with the declared variable name of the object. Java reflection allows to use the declared name via reflection to set the object member name. Just saves one parameter in hundreds of constructors.

I try to do the same in Kotlin but can't figure out how to do the property setting. Here is some simplified test code:

package myPackage

import kotlin.reflect.full.companionObject
import kotlin.reflect.full.declaredMemberProperties

class MyTestObject() {

  var name: String = "NotInitialized"

  companion object {
    val Anton = MyTestObject()
    val Berta = MyTestObject()
    val Caesar = MyTestObject()
  }
}

fun main(args : Array<String>) {
  println(MyTestObject.Anton.name) // name not yet initialized

  // Initialize 'name' with the variable name of the object:
  for (member in MyTestObject::class.companionObject!!.declaredMemberProperties) {
    if (member.returnType.toString() == "myPackage.MyTestObject") {
      println("$member: ${member.name}")

      // Set 'name' property to 'member.name':
      // ???
    }
  }

  println(MyTestObject.Anton.name) // now with the initialized name
}

The ??? line is where I would like to get access to the name property of MyTestObject to set it to to member.name. I'm looking for a function similar to (member.toObject() as MyTestObject).name = member.name.





How to know if a Type exist in .Net Framework or It's Developer-Defined type (Programaticly)? [duplicate]

I am working with reflection. When I get some type's properties, I want to distinguish the properties that it's property type is in .NetFramework library or is defined by the developer.

For example I want a method that is called :

bool IsDotNetType(Type t)

and for example int, string, DateTime, List etc are .Net types, BUT Student is developer defined.

I have used IsPrimitive method, but it just works for int, bool, string, and when I pass it DateTime, it says that it is not primitive

Thanks.





Attribute contents extracion

I'm trying to simplify code for extracting data from property attribute.

Attribute:

[AttributeUsage(AttributeTargets.Property)]
class NameAttribute : Attribute
{
    public string Name { get; }

    public ColumnAttribute(string name)
    {
        Name = name;
    }
}

Attribute contents extraction code ( null-checks removed ):

public static string GetName<T>(string propName)
{
    var propertyInfo = typeof(T).GetProperty(propName);
    var nameAttribute = (NameAttribute)propertyInfo.GetCustomAttributes(typeof(NameAttribute)).FirstOrDefault();
    return nameAttribute.Name;
}

Sample class:

class TestClass
{
    [Column("SomeName")]
    public object NamedProperty { get; set; }
}

Call sample:

var name = GetName<TestClass>(nameof(TestClass.NamedProperty))

Is it any way to rewrite attribute contents extraction method to simplify/shorten its call. It's too inconvenient for me due to its length.

Something like CallerMemberNameAttribute would be great but i found nothing.





jeudi 19 octobre 2017

How to load a class, with function, from DLL, at run-time, and detect that function's argument type?

How can I export a class, with a single member method, from a C# DLL in such a way that an application that loads that DLL can determine the parameter type of that member method? I'm currently using MEF to assist with export and import discovery of types.

I've created an interface so that I can specify that the class, in the DLL, has a method called Run. So just something like ...

public interface IPlugin
{
  void Run(object args);
}

My current predicament is that I want that Run function to specify its actual parameter type. So, each DLL ("plugin" in my scenario, because I guess I'm going after some basic plugin architecture) would export a class type that subscribes to IPlugin, but would be able to also specify the parameter type. I need to pass in a bit of data into each plugin, and I want to use data transport class types to do so. So, in reality, I'd like to have some various DLLs that would export classes like this ...

public class CatPlugin : IPlugin
{
  void Run(CatPluginPayload payload)
  {
    Console.WriteLine(payload.Age);
  }
}

public class DogPlugin : IPlugin
{
  void Run(DogPluginPayload payload)
  {
    Console.WriteLine(payload.Name);
  }
}

And so on ... with the focus being on the parameter type changing.

I need to be able to load these classes, from my application, at run-time, and be able to call the Run function and pass in the appropriate type.

Like I mentioned earlier, I am using MEF to assist with the exporting and importing, but I don't see that it can assist me with this, because this seems to require a generic interface or something.

How can I achieve what I'm aiming for?





Why is reflect Type.Implements() so much slower than a type assertion?

I'm trying to efficiently test whether an interface{} implements a given function and my solution is to create an interface with just this function and then check whether the interface{} implements this single function interface. The two options here seem to be either using reflection or a type assertion. Both seem to have identical behaviour however there is a large speed difference.

Looking at the code for Value.Implements() it does a linear scan over the functions defined on the value and compares them against the interface. The type assertion however just seems to do a constant time comparison (independent of the number of functions in the interface).

Is there a reason why Implements() doesn't just do a type assertion?

Benchmark:

package benchmarks

import (
    "reflect"
    "testing"
)

type ITest interface {
    Foo()
}

type Base struct{}

func (Base) A() {}
func (Base) B() {}
func (Base) C() {}
func (Base) D() {}
func (Base) E() {}
func (Base) F() {}
func (Base) G() {}
func (Base) H() {}
func (Base) I() {}
func (Base) J() {}

var Interface = reflect.TypeOf((*ITest)(nil)).Elem()

func BenchmarkReflection(b *testing.B) {
    var iface interface{}
    iface = Base{}
    for i := 0; i < b.N; i++ {
        if reflect.TypeOf(iface).Implements(Interface) {
            b.FailNow()
        }
    }
}

func BenchmarkAssertion(b *testing.B) {
    var iface interface{}
    iface = Base{}
    for i := 0; i < b.N; i++ {
        if _, ok := iface.(ITest); ok {
            b.FailNow()
        }
    }
}

Results:

go test -run=XXX -bench=. so_test.go
goos: linux
goarch: amd64
BenchmarkReflection-8           10000000                  208 ns/op
BenchmarkAssertion-8            200000000                9.24 ns/op
PASS
ok      command-line-arguments  5.115s





Kotlin: Compare property values of different target objects with(out) reflection

I want to compare values between multiple instances of a data class so that I know which value changed:

data class A(val name : String)
val firstA = A("hello")
val secondA = A("you")

if (secondA.name.changed(firstA)) {
   // Do something
}

Can I somehow access the property function of .name and execute it on another target value (in this example on firstA) without explicitly defining it? Can delegates help here or how do I solve this with and without reflection?





Reflection with winmd file

I want to use the reflection process in my c# app with

System.Reflection.Assembly.Load()

My problem is I don't want to use it with a .DLL file but with a .winmd file (in my case Windows.winmd).

Is it possible ?





Reflection dependency conflicts in runtime

Thanks in advance for the help.

I have the following situation:

I'm developing my extension plugin for druid which will handle druid log tasks and will store log data to elasticsearch. The druid itself load extension plugins through reflection that means what they all are in the same JVM machine. So, the currently problem is that my extension plugin uses elasticsearch dependency which in its turn uses com.google.guava dependency version 18.0 but druid has this dependency of version 16.1. In runtime my extension plugin uses older version 16.1 but I strongly need 18.0 because my implementation is for version 18.0 of guava library.

I receive a such of exception:

NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor conflits on Elastic Search jar

Notice: My project is created as maven project also I compile my extension plugin as shaded jar. Ideally it would be nice to say to druid that you must use your version 16.1 but left my extension plugin to use its version which is needed.

Do you have any ideas guys how to solve it?

Notice: If this information is not enough for you just tell me what you need more I'll try to provide more info.





LINQ to SQL Reflection in Select

I've got the following problem. I have table in a SQL database which looks like this:

| id | attr0 | attr1 | attr2 | attr3 | attr4 | attr5 |

So, I want to get the data from this table in a for loop.

I've created the class

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

And now i want to get all the attributes from table into one list

List<Attribute> attributeList = new List<Attribute>();
for(int i=0; i<6;i++)
{
    attributeList.Add((from a in db.Attributes
                  select new Attribute{
                      Id = a.Id,
                      Description = a.attr0}).First(); //How to use here i instead a fixed column name?
}

Is it possible to use i and get all attributes with one loop?

I was trying to use reflection but the compiler gives me an error, the code for that was:

for(int i=0; i<6;i++)
{
    attributeList.Add((from a in db.Attributes
                  select new Attribute{
                      Id = a.Id,
                      Description = a.GetType().GetProperty("attr"+i).GetValue(a,null))}).First();

UPDATE: The error is:

LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object, System.Object[])' method, and this method cannot be translated into a store expression.





mercredi 18 octobre 2017

Why does GetMethod("ToString") return null?

I am currently learning C# Generics and reflection. I want to call a method "toString" of a generic class T. The problem is that my program crashes with a null point exception - "nameMethod" variable below is null and I cannot figure out why "t.GetMethod("toString");" call below returns null. This is my code:

public class ViewModel<T> where T: EntityBase
{

    public ViewModel()
    {
        T _model = Activator.CreateInstance<T>();
        Type t = typeof(T);
        MethodInfo nameMethod = t.GetMethod("ToString");

        Console.WriteLine(nameMethod.Invoke(_model, null));
    }
}

BasePlant class:

public class BasePlant : EntityBase
{
    public string GetName => "TESTING NAME METHOD";

    public override string ToString()
    {
        return GetName;
    }
}

Usage:

 static void Main(string[] args)
    {
        var vm = new ViewModel<BasePlant>();

        Console.ReadKey();
    }

I am stuck at this crash and I am not sure what I am doing wrong. I would appreciate any help.





System.NotSupportedException: ''DataSet' supports not System.Nullable<>

I am retrieving propertyInfos from a given type.

When a property is of type Nullable then I can not add the property type to the dataTable.columns collection because I get an exception:

System.NotSupportedException: ''DataSet' supports not System.Nullable<>.'

foreach (var prop in propertyInfos)
            {
                if (prop.PropertyType == typeof(int?))
                {

                    dataTable.Columns.Add(prop.Name, prop.PropertyType);
                }
                else
                {
                    dataTable.Columns.Add(prop.Name, prop.PropertyType);

                }
            }

What should I change in the if-clause to make it work?

I already added null or DBNull to the collection but that did not help?!





mardi 17 octobre 2017

Create instance of List using reflection c#

I work on method which will dynamically creates instances of collections in our entities. My problem is when I create new record which has to be inserted into database, my ICollection navigation properties are always null and in my safe method

I have to use something like this below to create new List and its definitely not good approach. If I dont create instance of List, Mapper will throw error that it cannot map Collection of something to null, for example it cannot map List of Categories to null.

Sample of my safe method

//check if record exists in database so i know if have to update or insert record (based on entity Id)
var entity = repository.GetById(detail.Id)
//....some code removed for brevity
if (entity.Categories == null)
{
    entity.Categories = new List<Category>();
}
if (entity.UserContacts == null)
{
    entity.UserContacts = new List<UserContact>();
}
//dto => entity
Mapper.PopulateEntity(dto, entity);
//update or insert later on.

Extension method which has to create instance of List<T> for example new List<Category>() like its shown above.

public TEntity InitializeEntity(TEntity entity)
    {
        var properties = entity.GetType().GetProperties();
        foreach (var prop in properties)
        {
            if (typeof(ICollection<TEntity>).Name == (prop.PropertyType.Name))
            {   
                var get = prop.GetGetMethod();
                //get assembly with entity namespace and class name
                var fullName = get.GetBaseDefinition().ReturnType.GenericTypeArguments[0].AssemblyQualifiedName;

                //create instance of object
                var myObj = Activator.CreateInstance(Type.GetType(fullName));

                //check if property is null or if get some value, dont want to rewrite values from database
                var value = prop.GetValue(entity);
                if (value == null)
                {
                    var listType = typeof(List<>);
                    var constructedListType = listType.MakeGenericType(myObj.GetType());
                    Activator.CreateInstance(constructedListType);
                }
            }
        }
        return entity;
    }

For some reason its not creating any instances at all and I cannot figure out where is problem.





java get all extended interfaces from base interface

Is it possible to get list of all interfaces which extends base interface without having any bean implemented any interface in java at runtime?

Example:

interface A {}
interface B extends A{}
interface C extends A{}
interface D extends C{}

public Class<? extends A>[] getAllInterfaces(A.class);

Method getAllInterfaces() should return all interfaces which extends A: {B, C, D}





getDeclaredConstructor doesn't find constructor with interface as parameter

I have an interface

public interface IDrawing

Next I have a class implementing this interface:

public class Line implements IDrawing

Now I have a class with a constructor that accepts above as parameter:

public LineChanger(Line line)

No problems there.

When I use reflection to call above constructor, it throws a NoSuchMethodException

//drawing variable is of class Line implementing IDrawing
.getDeclaredConstructor(IDrawing.class).newInstance(drawing);

The exception goes away when I change the constructor to:

public LineChanger(IDrawing line)

Is it possible to get the reflection working without changing the constructor?

I wish to keep the constructor strict (i.e. only accept one specific class in this case Line) but keep the reflection working for my factories.