mercredi 30 septembre 2015

How to generically retrieve all children of a certain type in a root layout?

What I mean by my question (if I stated it ambiguously, as I couldn't find an answer to my question) is to take a root layout, get all children of that layout, and perform a callback on any that are an instanceof the specified type.

Now, I can do it in a fixed way, easily by doing something like...

RelativeLayout root = (RelativeLayout) findViewById(R.id.root_layout);
    for(int i = 0; i <= root.getChildCount(); i++){
        View v = root.getChildAt(i);
        if(v instanceof CustomLayout){
            // Do Callback on view.
        }
    }

Thing is, I want to make it more generic. I should be able to use any layout, and check to see if it is an instance of any layout. In particular, I want it generic enough to be used with anything (if this is even possible). Of course I don't mind stopping at just settling for layouts.

I want to build a collection of these children and return them, if possible of the same type. I haven't done Java in a long while so I'm very rusty, but I was thinking of using reflection to accomplish this. Is this at all possible?

If I pass the class of the type I want, is it possible?





Java reflections to get fields that are constants in interface class

I have a Java class "MyClass" which implements an interface "MyInterface". The "MyInterface" class has only constant fields(~200 fields in it).

public interface MyInterface {
public final static int NUM = 1111;
public final static String mystring = "1.1.0";
public final static int my_set1_1 = (0x0100000|4);
public final static int my_set1_2 = (0x0100000|6);
public final static int my_set2_1 = (0x001000|4);
public final static int my_set2_2 = (0x001000|6);
.
.
.
}

public MyClass implement MyInterface {
}

I am now trying to use reflection to get the constants that are declared in "MyInterface" class.

However I am unable to get the fields from the interface, irrespective of if I use getFields() or getDeclaredFields().

I tried using MyClass.getDeclaredFields() and also tried to use MyInterface.getDeclaredFields(). However I am unable to get the constants in Interface class.

Is there a way to get this?? Any ideas? Following is the code snippet of how I am trying to achieve this-

for (Class<?> currentClass = this.getClass(); currentClass != null; currentClass = currentClass.getSuperclass()) {
            Class<?>[] InterfaceClass = currentClass.getInterfaces();
            if (Arrays.asList(InterfaceClass).contains(MyInterface.class)) {
            for (Field field : currentClass.getDeclaredFields()) {
                if(field.getType() == int.class) {
                    //Do nothing
                }
            }
        }

    }





Retrieve the names of (and default values of) the arguments accepted by a specified function

Say I have a function, foo which has some arguments...some positional and some keyword:

def foo(a, b=1.0, c=None):
    print a
    print c
    return 2 * b

Is there another function I can call with foo as an argument (or a method of foo which I can call) that will return to me a list of the positional arguments of foo as well as a list of tuples of the keyword arguments of foo along with their default values? Specifically, calling:

the_function_i_want(foo)

should return

(('a',), (('b', 1.0), ('c', None)))

Or something like that. To be clear I do not want a way to figure out what values were passed to foo one particular time that it was called. Instead I want information about the function signature of foo in a programatic way.

(The use case I have in mind is to automatically make a web form which will be able to submit appropriate data to serve as the arguments of a specified function. So that if I call web_form(foo) in the appropriate way, it will be able to render a web form with spaces for each of the arguments of foo with the default calling values pre-filled in an appropriate way.)





Using a ClassName as a parameter in C#

I have searched the current questions and none seemed to solve my particular issue.

I have several classes that contain validation methods in them : ClientValidation, PaymentValidation, etc. The plan is to dynamically build a list of methods that I would use to validate a record. To do this I need to be able to get a list of the methods contained within each class. To do that I have written the following line:

var methods = typeof( ClientValidation ).GetMethods();

This works great if all my methods were under the ClientValidation class, but they are not. What I want to be able to do is be able to dynmically pass in the class name so the line could look more like:

var dynamicClassName = GetClassNameMethod();

var methods = typeof( dynamicClassName ).GetMethods();

Is this possible? How would I do this?

Thanks in advance.





Haxe CreateInstance and Properties

I want to deserialize an object with properties. The object is well constructed but setters/getters are not correctly instancied if I don't type explicitly my object.

Is it an intended behavior or a bug ?

Minimal example:

package models;
class TestClass
{
    public var test(default, set): String;
    public function set_test(myVar) {
        trace("Set " + myVar);
        return test = myVar;
    }
}

class Main
{
    public function new() 
    {
       var typedTest: TestClass = Type.createInstance(Type.resolveClass("models.TestClass"), []);
       var untypedTest = Type.createInstance(Type.resolveClass("models.TestClass"), []);
       trace(Type.getClassName(Type.getClass(typedTest)));   //"models.TestClass"
       trace(Type.getClassName(Type.getClass(untypedTest )));  //"models.TestClass"
       typedTest.test = "12";  // "Set 12"
       untypedTest.test = "15"; //nothing happens here
       Reflect.setProperty(untypedTest, "test", "18"); // "Set 18"
    }
}

I'm kinda confused about this one.





How to make Java agent and reflection work together?

I have a project (http://ift.tt/1M1JxjO) that uses java-agent for online instrumentation. I tried to have an annotation class for runtime reflection. The program crashes with NoClassDefFoundError

Exception in thread "main" java.lang.NoClassDefFoundError: janala/logger/DJVM
at com.sun.proxy.$Proxy0.<clinit>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:739)
at sun.reflect.annotation.AnnotationParser$1.run(AnnotationParser.java:305)
at sun.reflect.annotation.AnnotationParser$1.run(AnnotationParser.java:303)
at java.security.AccessController.doPrivileged(Native Method)
at sun.reflect.annotation.AnnotationParser.annotationForMap(AnnotationParser.java:303)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:293)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
at sun.reflect.annotation.AnnotationParser.parseSelectAnnotations(AnnotationParser.java:101)
at sun.reflect.annotation.AnnotationType.<init>(AnnotationType.java:139)
at sun.reflect.annotation.AnnotationType.getInstance(AnnotationType.java:85)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:266)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
at java.lang.reflect.Executable.declaredAnnotations(Executable.java:546)
at java.lang.reflect.Executable.getAnnotation(Executable.java:520)
at java.lang.reflect.Method.getAnnotation(Method.java:607)
at janala.utils.ClassRunner.run(ClassRunner.java:20)
at janala.utils.ClassRunner.main(ClassRunner.java:33)

The call site of the error is simply

Test annotation = method.getAnnotation(Test.class);

If I change the program to first instrument the class, write the instrumented class to a .class file and then run the program with the same classpath. Then it runs fine.

The annotation is declared as

public class Annotations {

   /**
   * A CATG test.
   */
  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.METHOD)
  public @interface Test {}
}

And the use of the annotation is like

  @Test
  public void testAnd() {





Skip generation of readonly fields for Html.ActionLink

I have a base request-object RequestBase defined like:

public abstract class RequestBase
{
    public abstract string Area { get; }
    public abstract string ActionName { get; }
    public abstract string LinkName { get; }
    public abstract string ControllerName { get; }
}

and a childclass of this like:

public class RequestTest : RequestBase
{
    public Guid Id { get; set; }

    public RequestTest()
    {
        Id = Guid.Empty;
    }

    #region implementation of RequestBase

    public override string Area
    {
        get { return "MyArea"; }
    }

    public override string ActionName
    {
        get { return "Overview"; }
    }

    public override string ControllerName
    {
        get { return "Test"; }
    }

    public override string LinkName
    {
        get { return "Click me for awesome"; }
    }

    #endregion
}

Question. I want to write a helper to build links this way:

@Html.ActionLinkByRequest(new RequestTest{Id = Guid.Empty})

which I currently have implemented

public static MvcHtmlString ActionLinkByRequest(this HtmlHelper helper, RequestBase request, object htmlAttributes = null)
{
    return helper.ActionLink(request.LinkName, request.ActionName, request.ControllerName, request, htmlAttributes);
}

Unfortunately it renders to:

<a href="/MyArea/Test/Overview?EventId=00000000-0000-0000-0000-000000000000&ActionName=Overview&LinkName=Click%20me%20for%20awesome&ControllerName=Test">Click me for awesome</a>

but I want to have only

<a href="/MyArea/Test/Overview?EventId=00000000-0000-0000-0000-000000000000">Click me for awesome</a>

without the readonly fields. Because they are readonly, I don't need them explicitly in the query-string as of my Action awaits the concrete implementation RequestTest and will have them anyway:

public ActionResult Overview(RequestTest request)
{
    // do things here

    return View();
}

Any ideas how I can skip the generation of read-only fields for the actionlink? Maybe by using reflection somehow?





Dynamically Flat C# object class List of properties at Runtime

I've a class A like that:

public class A
{
    private String id;              // Generated on server
    private DateTime timestamp;
    private int trash;
    private Humanity.FeedTypeEnum feedType
    private List<Property> properties;
// ...

where Property is:

public class Property
{
    private Humanity.PropertyTypeEnum type;
    private string key;
    private object value;
//...

I'd like to build a dynamic object that flat List<Property> properties A's field to raw properties. For example:

A a = new A();
a.Id = "Id";
a.Timestamp = DateTime.Now;
a.Trash = 2;
a.FeedType = Humanity.FeedTypeEnum.Mail;
a.Properties = new List<Property>()
{
    new Property()
    {
        Type = Humanity.PropertyTypeEnum.String,
        Key = "name"
        Value = "file1.pdf"
    },
    new Property()
    {
        Type = Humanity.PropertyTypeEnum.Timestamp,
        Key = "creationDate",
        Value = Datetime.Now
    }
}

As I've commented I'd like to flat this a object in order to access to the properties as:

String name = a.Name;
DateTime creationDate = a.CreationDate;
a.Name = "otherName";
a.CreationDate = creationDate.AddDays(1);

I've achieved that using Reflection. However, I'm figuring out that it's a best option using ExpandoObject.

The question is, how can I do that using ExpandoObject class?





How to cast Any to Array[T] maintaining Scala's invariance for arrays

I tried to implement the following function maintaining Scala's invariant view over the JVM arrays:

def cast[T](a: Any): Option[Array[T]] = ???

That is, given:

class Foo
class Bar extends Foo

the following examples should work and return Some:

val arr1: Any = Array(new Bar)
cast[Bar](arr1) // OK

val arr2: Any = Array(1, 2, 3)
cast[Int](arr2) // OK

val arr3: Any = Array("a", "b", "c")
cast[String](arr3) // OK

The following one, instead, should return None:

val arr: Any = Array(new Bar)
cast[Foo](arr1) // KO, violates invariance

I tried through reflection using ClassTag/TypeTag with no luck, but since I'm no reflection expert I could be missing something.





mardi 29 septembre 2015

Java: Reflection, Generic Types, and Unchecked Casts

My class will be given an Object class. I am then using reflection to iterate over the declared fields of that class and registering a ChangeListener on each field with the Property base class.

The original 'createChangeListener' method looked like this:

private void createChangeListener(Property property) {
    property.addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue observable, Object oldValue, Object newValue) {                        
            Foo.this.propertyChanged(observable);
        }
    });
}

However, this was producing an unwanted warning:

warning: [unchecked] unchecked call to addListener(ChangeListener<? super T>) as a member of the raw type ObservableValue
    property.addListener(new ChangeListener() {
        where T is a type-variable:
    T extends Object declared in interface ObservableValue

Not to be dissuaded, I provided a generic type for my Property parameter and ChangeListener:

private void createChangeListener(Property<Object> property) {
    property.addListener(new ChangeListener<Object>() {
        @Override
        public void changed(ObservableValue observable, Object oldValue, Object newValue) {                        
            Foo.this.propertyChanged(observable);
        }
    });
}

...Only now to be notified that I have simply shifted my problem to the source of the reflection. The code, below, is now modified to cast to Property<Object> from its original Property w/o a generic type:

if (Property.class.isAssignableFrom(field.getType())) {
    createChangeListener((Property<Object>)(field.get(model)));
}

This previously warningless code is now producing the head-tilting:

warning: [unchecked] unchecked cast
    createChangeListener((Property<Object>)(field.get(model)));
required: Property<Object>
found:    Object

Questions:

  • ಠ_ಠ
  • Given Java's type erasure limitations, what techniques are available to me to safely resolve these warnings?
  • Am I safe to suppress the unchecked warning in the original, non-typed method?




Getting System.Environment.OSVersion from Windows 8.1 phone via reflection

When I query field System.Environment.OSVersion in my Windows Phone it shows value {Microsoft Windows NT 8.10.14219/0} an it appears to be public, but I can't get the value in the code, since property OSVersion is not listed.

Can I get it using reflection?





Methods in Arrays for Java? Reflection?

I'm using Java, and wondering if it's possible to put methods directly into arrays as elements. Something like:

...[] arrayName = {herp(), derp(), jinkies()};

When I looked this up prior, some people mentioned "reflection," but I don't know what this is (I'm very new to programming). Is there a simple way to put methods into arrays (my goal is to spit them out randomly with a Random, and eventually terminate with a String parameter in each method named "quit" or something)? If not, how does reflection work for this circumstance (if at all)?

Thank you for your time.

[EDIT] I am NOT only asking what reflection is. My exact (main) question is "Is it possible to put methods into arrays," and if it is, how is that done? What is the syntax for it?





How to add Reflection for UNIX and OpenVMS reference to C#?

I am trying to add a reference to Reflection for UNIX and OpenVMS to my C# project but get the following error

A reference to 'Reflection for UNIX and OpenVMS' could not be added

enter image description here

Does this mean I do not have that library ? Why would it show up then ? Can I download it and then reference ? I could not find the libraries on their website .





MethodInfo's GetMethod for Dictionary objects's "Any" method [duplicate]

This question already has an answer here:

I am using below method to create the expression for searching a string in an entity

MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });

this works fine in the case of string. But when I tried with the Dictionary object as

MethodInfo method2 = typeof(Dictionary<string, string>).GetMethod("Any", new[] { typeof(Func<string,string>),typeof(bool)});

but it returns null value always. Anybody let me know how to use the method to get correct value of the MethodInfo





Executing a specific function based on a std::string

I am trying to write a program that will execute a function based on a string I fetch from a database. Basically what I do is:

// Create an enum
enum AFunc{
 invalidFunction,
 function2,
 function3
}

// have a class handling the functions
struct A
{
  static AFunc resolveStringToFunction(std::string) {...}

  template<int T>
  void execute(...)
  {
     // this may not be called = invalidFunction
  }

  template<>
  void execute<1> (...)
  { 
     // do stuff = function1
  }

  template<>
  void execute<2> (...)
  { 
     // do stuff = function2
  }
};

In my application i do this:

A a;
std::string funcString = getFromDatabase (...) // Not really, but this is abstract
const AFunc funcType   = A::resolveStringToFunction(funcString);

a.execute<funcType>(...);

The problem here is that the compiler does not accept the dynamic calling of a template function, because (as I understood it) it needs to know which function is called by compile time.

Is there any way around this?

Is there a better solution to this problem? Maybe a design pattern?





Getting Exception while converting case class to Json using Json4s

I am trying to convert a case class to Json String using Json4s. I am getting the exception

MappingException: Can't find ScalaSig for class java.lang.Object

This is happening if I am extending my case class with another trait only.

My code is as below:

trait Integration {
  val thirdpartyId: Option[Long]
}

trait HrIntegration extends Integration {
  override val thirdpartyId: Option[Long] = getValue
  def getValue = {
    Some(100L)
  }
}

case class Employee(id: Long, name: String, age: Long) extends HrIntegration


object Test extends App {
  import org.json4s.Extraction
  import org.json4s.jackson.JsonMethods._
  import org.json4s.DefaultFormats
  implicit lazy val serializerFormats = DefaultFormats
  val emp = Employee(1, "Yadu", 27)
  val jValue = Extraction.decompose(emp)
  val jsonString = compact(jValue)
  println(jsonString)
}

If I convert Option[Long] to Option[BigInt], it works fine. The same issue is with Option[Double] as well.

When I went through the stacktrace and subsequent googling, I found that the issue is with the reflection, due to scala version mismatch. So I added scala reflect library dependency as below:

"org.scala-lang" % "scala-reflect" % "2.11.7",
"org.scala-lang" % "scalap" % "2.11.7"

But even after that, I am getting the same error. I have fixed the issue for now by using BigInt and BigDecimal instead of Long and Double.

Can someone please help me to understand the issue and how I can fix it by using Long and Double itself.

Json4s Version : 3.2.11
Scala Version : 2.11.7





Using reflection

I am experiencing this problem

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)

when invoking a method through reflection

 method.invoke(null, input.get(i), result.get(i));





lundi 28 septembre 2015

Address an int[] array from a class through a different class and is also constructed from a string?

The important bit is the construction of the reference using a string. ie, I need to get access to that int[] from the construction of a string.

For example using "myClass ["int"+myString]" to access myClass.intArray

What am I doing wrong? How can I do this?

 using UnityEngine;
 using System;
 using System.Collections;
 using System.Collections.Generic;

 public class MyClass : MonoBehaviour {

 public int[] intArray = new int[3]{1,2,3};
 }

 //---------------------------------------------------------------------------

 using UnityEngine;
 using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.Reflection;

 public class MyOtherClass : MonoBehaviour {
     MyClass myClass;

     void theMethod(string myString){
          myClass = GetComponent<MyClass> ();

//-->Error is here://

          int[] theArray = myClass.GetType ().GetFields (myClass ["int"+myString]);

//--//

          theArray[0] = 4;
     }

     void Awake(){ theMethod("Array"); }
 }





A class loaded at runtime cannot find a class inside a JAR file which is inside a folder Lib

Its tricky to explain. I have a JAR file framework.jar which loads a class sikuli.class from a folder Libraries and executes a function xyz() Now this sikuli.class file uses some other JAR files which are API

I have added these APIs while creating the framework.jar and bundled them inside it.

but when I am executing the JAR file it says ClassNotFound for all the import statements inside the sikuli.class file

I tried adding the API JAR files to CLASSPATH also, even that didn't work.





Node.js - searching for the "util" module; identify core modules

I'm really a big fan of Swagger's node module, but one thing is driving me crazy:

The sample app contains the following line (api/controller/hello_world.js):

var util = require('util');

But I just can't find this module. I tried to

  • list it with npm list but nothing
  • search for it with Spotlight (util.js)

My question is: How can I list the actually loaded modules in nodejs?





Reflection vs reference - IoC container registering

I have some IoC container (it doesn't matter which one, but lets assume it is Autofac). In my solution I have more than 30 services which need to be registered. All services resides in the same assembly called Services and each class has a name in format {specific_name}Service.cs.

I'd like to avoid for some reasons registering each service manually this way:

container.Register<OneService>().AsSelf();
container.Register<TwoService>().AsSelf();
...
container.Register<ThirtyFourService>().AsSelf();

And register my types in this way:

Type[] serviceTypes = Assembly.Load("Services")
                      .GetTypes()
                      .Where(t => t.Name.EndsWith("Service"))
                      .ToList();

foreach(Type serviceType in serviceTypes)
{
    container.Register(serviceType).AsSelf();
}

All I want achive is minimalistic registration process which allows me add or remove services and keep source code clean. Initialization of my application can be slow (server side application), but when first request comes, it has to behave as quick as possible (performance does really matter at serving responses). Saying initialization I mean registering types, reading configuration files, etc.

Does such reflection usage slow my application "at runtime" or just impact app initialization? How dependencies will be resolved later?





Android intercept internal librairie method call

I have sdk of logging android.
Client (app) can use other logging sdk like mine. I want to handle the call of external method log. For example, I want to log "Hello word" for each call of Log.i. I have some idea for intercept (MethodInvocationHandler).





Why I am getting the exception when generating JPA objects at run time?

ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(JpaRepository.class));
CtClass superClass = pool.get(JpaRepository.class.getName());
superClass.setGenericSignature("<T:Ljava/lang/Object;ID::Ljava/io/Serializable;>Ljava/lang/Object;Lorg/springframework/data/repository/PagingAndSortingRepository<Lcom/his/jtec/domain/Gender;Ljava/lang/Long;>;");
CtClass cc = pool.makeInterface("com.his.jtec.domain.GenderRepo");
cc.defrost();
cc.setSuperclass(superClass);

ConstPool constpool = cc.getClassFile().getConstPool();
AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
Annotation annot = new Annotation("Inject", constpool);
attr.addAnnotation(annot);
cc.getClassFile().addAttribute(attr);

repositoryClass = cc.toClass();
Method method = repositoryClass.getMethod("findAll", (Class<?>[])null);
responseMsg = method.invoke(repositoryClass.getClass());  

java.lang.IllegalArgumentException: object is not an instance of declaring class 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:497)





How to query on a generic model using EF 6

I am developing an MVC 5 application. I query on my database as:

var result = db.ABCs.AsNoTracking().FirstOrDefault(e => e.Id == Id);

But what if I want to make a generic method and Don't know the name of the model on compile time. I want to query on any model class that is passed to a method at runtime. Something as :

var result = db.<T>.Where(x => x.Id == Id).ToList();

How can I do that. I am using database first approach and no repositories or UoW.





Looping through Generic Class's collection property

Although many questions have been posted, none seem to help me on my issue.

I've started a new Generics / Reflection adventure and I'm just trying to get my head around the syntax and concepts.

I have a Generic class with X amount of properties and one being a collection, all is working fine but I'm having problems extracting the values from the collection props by property name.

foreach (var property in typeof(T).GetProperties())
{
    if (property.Name == "Props")
    {
        foreach (var item in (IEnumerable)property.GetValue(type, null))
        {
            var propertyName = "";
            var newValue = "";
            var oldValue = "";

            sbDescription.AppendLine(strDescriptionVals
               .Replace("{0}", (item.ToString() == "PropertyName") ? item.ToString() : "" + ", "));

            sbAllNotes.AppendLine(strAllNotes
               .Replace("{0}", (item.ToString() == "PropertyName") ? item.ToString() : "")
               .Replace("{1}", (item.ToString() == "NewValue") ? item.ToString() : "")
               .Replace("{2}", (item.ToString() == "OldValue") ? item.ToString() : ""));
        }
    }
}

As you can see I've pinpointed the property Props and now I want to loop through that and pull values by property name.

item.ToString() just prints the namespace of the class property and not the value

Hoping you kind folk can point me in the right direction?





Common action executed for multiple getters

I'm trying to find a neat way to trigger a loading mechanism when one of several getters is first accessed. My first thoughts are about something like this:

public class Customer {
    private bool loaded = false;

    public int PK { get; set; }
    public string Email { get; set; }

    public string Name { get { if (!loaded) loadData(); return _name; } set { ... } }
    public string Street { get { if (!loaded) loadData(); return _street; } set { ... } }
    public string City { get { if (!loaded) loadData(); return _city; } set { ... } }
}

In short, in this example every Customer exists with its base data PK and Email until one of the other properties is accessed.

This would mean much duplicate code, increasing with the complexity of the class. Is there a way to create some kind of inheritance for these properties?

Something like this, but I don't think this is possible:

private void checkData() { if (!loaded) loadData(); }
public string Name:checkData { get; set; }
public string Street:checkData { get; set; }
public string City:checkData { get; set; }

Another way might be possible through reflection, but as I'm not experienced with it I don't know where to start here.

Any hints are deeply appreciated! ;-)





return Class.forName instead of new instance

I've found this code inside an old project

public abstract class AireBatchDaoFactory {
     public static final String ORACLE_FACTORY = "airebatch.oracle.OracleDaoFactory";
     public static AireBatchDaoFactory getFactory(String factory) throws SQLException
     {
        try {
           return (AireBatchDaoFactory) Class.forName(factory).newInstance();
        } 
        catch (Exception e) {
            throw new SQLException("error msg");
        }
     }
     public abstract AireBatchDao getAireBatchDao() throws SQLException;}

I would like to understand the concrete difference beetween

return (AireBatchDaoFactory) Class.forName(factory).newInstance();

and

return new AireBatchDaoFactory();





Scala - reflectively invoke private static method from Java

I'm trying to take a private static method from a Java class and invoke it in Scala. Here's the code I have so far:

val blockClass = classOf[Block]
val aMethod: Method = blockClass.getDeclaredMethod("a", Integer.TYPE, classOf[String], classOf[Block])
aMethod.setAccessible(true)

aMethod.invoke(null, 145, "anvil", anvilPatch)

When I try to compile this, however, I get this error:

Error: the result type of an implicit conversion must be more specific than AnyRef
aMethod.invoke(null, 145, "anvil", null)
                     ^

That 145 is supposed to be a Java int, and Integer.TYPE is the only thing I could think of to get a Java int.

Any ideas?





Get ctor argument used in field's initializer using reflection

My assembly has multiple classes which have fields like this:

private static Foo MyFoo = new Foo(typeof(Bar));

The argument typeof(Bar) differs for each class.

In my unit tests, I need to extract that argument dynamically.

I can find all classes, and filter for those with a static Foo field. I then have a FieldInfo.

But then I don't know how to get that argument?

What I'm doing so far:

var argument =
  Assembly.GetExecutingAssembly().Select(name => Assembly.Load(name.FullName))
  .SelectMany(assembly => assembly.GetTypes()).Where(type => type.IsClass)
  .Where(type => type.GetFields(BindingFlags.Static).Any(fieldinfo => fieldinfo.FieldType == typeof(Foo)))
  .Select(fieldinfo => fieldinfo.FieldType == typeof(Foo));





dimanche 27 septembre 2015

C# LINQ select properties with specific attribute value

I'm looking for a way to select properties that have specific customattributes with specific values in a single LINQ Statement.

I got the properties that have the attribute that I want, but I have no clue how to select it's specific value.

<AttributeUsage(AttributeTargets.Property)>
Public Class PropertyIsMailHeaderParamAttribute
    Inherits System.Attribute

    Public Property HeaderAttribute As String = Nothing
    Public Property Type As ParamType = Nothing

    Public Sub New()

    End Sub

    Public Sub New(ByVal headerAttribute As String, ByVal type As ParamType)
        Me.HeaderAttribute = headerAttribute
        Me.Type = type
    End Sub

    Public Enum ParamType
        base = 1
        open
        closed
    End Enum
    End Class


    private MsgData setBaseProperties(MimeMessage mailItem, string fileName)
    {
        var msgData = new MsgData();
        Type type = msgData.GetType();
        var props = from p in this.GetType().GetProperties()
                    let attr = p.GetCustomAttributes(typeof(Business.IT._21c.AddonFW.PropertyIsMailHeaderAttribute), true)
                    where attr.Length == 1
                    select new { Property = p, Attribute = attr.FirstOrDefault() as Business.IT._21c.AddonFW.PropertyIsMailHeaderAttribute };
    }





java: Is it possible to know which constructor an enumeration item uses to be initialized?

Just as the title say, I was wondering if it is programmatically possible to get to know the constructor that an enumeration item uses to be initialized, I think that if there is such mechanism it should be accessible by using reflection but I have not been able to find anything like that, to be more specific:

What I have

enum AnEnum {

    E1(1),
    E1(1, 2);

    int v;

    AnEnum(int p1) {
        v = p1;
    }

    AnEnum(int p1, int p2) {
        v = p1 + p2;
    }

} 

What I need is a mechanism to tell me whether the instance was initialized by using the one or the two argument constructor, and even better would be if I can get the parameters used to initialize it.





Variable Reference Via String With Method Invocation In Java

I have been searching on here for several days and have come close to what I was hoping existed although not exactly.

I have a GUI that has a TabbedPane section containing several tabs that in turn have several JSpinners. The tabs are identical in structure and the spinners are named using the following naming convention [prefix]Spinner][num] (ex. Tab 1: redSpinner1, blueSpinner1.. Tab 2: redSpinner2, blueSpinner2.. and so on). I need to extract the values of the spinners on each tab and wanted to do it by "building" the variable name via concatenation of the prefix, "Spinner" and the incremented value that is the tab number that the spinner is located on. My goal is to not have to hard code the variable names yet still be able to access the variable methods, specifically getValue().

In my research I have come across two possible solutions:

1) Using a Map structure to map the variable name to the actual instance

2) Reflection API

The first method I can use my method of variable name concatenation for the key but will still have to manual map the instance variable name. Ultimately this puts me in the same position I am already in.

Full disclosure, I am not an expert in the reflection API, so I may not understand it sufficiently enough to solve my issue (hence why I am on here!). I have attempted/desire to do the following (or something close to it):

Class myClass = GuiClass.class; //GuiClass == main gui class containing spinners
Field myField = myClass.getField(redSpinner1); //using the 'built variable name'
int myValue = (int) myField.getValue(); //I can't get this step to work.

Any help would be greatly appreciated. I am beginning to think that I may have to change the design of that sections structure and want to see if anyone on SE has a better way. Thank you in advance.





One parameter of custom class is re-written

I have a custom class for triangles:

[XmlRootAttribute(Namespace = "", IsNullable = false)]
[XmlType("Figure.Triangle")]
public class Triangle : Figure
{
    [XmlIgnore]
    public Point a { get; set; }
    [XmlIgnore]
    public Point b { get; set; }
    [XmlIgnore]
    public Point c { get; set; }

    [XmlElement("a")]
    public string aString
    {
        get { return a.X.ToString() + ';' + a.Y.ToString(); }
        set
        {
            if (String.IsNullOrWhiteSpace(value))
                return;
            string[] xmlArr = value.Split(';');
            this.a = new Point(Convert.ToInt32(xmlArr[0]), Convert.ToInt32(xmlArr[1]));
        }
    }

    [XmlElement("b")]
    public string bString
    {
        get { return b.X.ToString() + ';' + b.Y.ToString(); }
        set
        {
            if (String.IsNullOrWhiteSpace(value))
                return;
            string[] xmlArr = value.Split(';');
            this.b = new Point(Convert.ToInt32(xmlArr[0]), Convert.ToInt32(xmlArr[1]));
        }
    }

    [XmlElement("c")]
    public string cString
    {
        get { return c.X.ToString() + ';' + c.Y.ToString(); }
        set
        {
            if (String.IsNullOrWhiteSpace(value))
                return;
            string[] xmlArr = value.Split(';');
            this.c = new Point(Convert.ToInt32(xmlArr[0]), Convert.ToInt32(xmlArr[1]));
        }
    }

    [XmlIgnore]
    public Pen pen { get; set; }
    [XmlElement("PenColor")]
    public int penColor
    {
        get { return pen.Color.ToArgb(); }
        set { this.pen.Color = Color.FromArgb(value); }
    }

    [XmlElement("PenWidth")]
    public float penWidth
    {
        get { return this.pen.Width; }
        set { this.pen.Width = value; }
    }

    [XmlIgnore]
    public SolidBrush brush { get; set; }
    [XmlElement("BrushColor")]
    public int brushColor
    { 
        get { return this.brush.Color.ToArgb();}
        set { this.brush.Color = Color.FromArgb(value); }
    }
    public Triangle()
    {
        a = new Point(0, 0);
        b = new Point(0, 0);
        c = new Point(0, 0);
        pen = new Pen(Color.Black, 1);
    }

    public Triangle(Point a1, Point b1, Point c1, Pen myPen)
    {
        this.a = a1;
        this.b = b1;
        this.c = c1;
        this.pen = myPen;
    }
}

I serialize my figures to the xml-structure and save them. If I need I deserialize them back and re-draw in the pictureBox. The issue is: when I deserialize figures from xml, all filled figures have the color of the last one.

Here's part of deserialization:

foreach (XmlNode singleNode in nodes)
{
    Type TestType = GetTypeFromAssemblyByName(singleNode.Attributes.GetNamedItem("d1p1:type").Value);
    if (TestType != null)
    {
        ConstructorInfo ci = TestType.GetConstructor(new Type[] { });
        object Obj = ci.Invoke(new object[] { });
        MethodInfo method = TestType.GetMethod("Deserialize");
        object result = method.Invoke(Obj, new object[] { singleNode.OuterXml });                      
        listObjects.Add(result);
    }
    else
    {
        Console.WriteLine("Class wasn't found");
    }
}

E.g. I have 2 filled triangles which are saved to Xml. First is blue and second is red and both of them have different brush color, which is need for fillPolygon method.

<Workspace>
  <Figure d1p1:type="Figure.FilledTriangle" xmlns:d1p1="http://ift.tt/ra1lAU">
    <a>64;68</a>
    <b>96;295</b>
    <c>283;41</c>
    <PenColor>-16777216</PenColor>
    <PenWidth>1</PenWidth>
    <BrushColor>-16744193</BrushColor>
  </Figure>
  <Figure d1p1:type="Figure.FilledTriangle" xmlns:d1p1="http://ift.tt/ra1lAU">
    <a>321;411</a>
    <b>575;152</b>
    <c>629;462</c>
    <PenColor>-16777216</PenColor>
    <PenWidth>1</PenWidth>
    <BrushColor>-65408</BrushColor>
  </Figure>
</Workspace>

Everything seems right, but when I invoke the Deserialize method, the result is, that the brush color of all previously added figures in the list is re-written. So in my example I have two red triangles on theirs right positions.

I understand that list contains references to the result, but other parameters: coordinates, pen color, etc are left as they were.

How can I get rid of this? I've tried to write result values to array, but even in the array they were replaced.





Swift 2.0 Reflection on Metatype

Swift reflection works great on an instance of a particular type but what if I want to print out all the instance variables of a particular class?

Creating a Mirror works for an instance:

Mirror(reflecting: self).children.filter { $0.label != nil }.map { return $0.label! }

but when self is a class like Bird or Fruit, the list returned is empty.





samedi 26 septembre 2015

how to get the property name after by comparing it with a string name in EF6

I am developing an MVC 5 application and I needed to maintain a log of all the changes so I get the following function to make a list of all changes happened to a document at the time of submission. It get the original entities and modified as parameter and then return which values are changed by what.

public static IEnumerable<KeyValuePair<string, object>> ModifiedValues<T>(this T obj, T modifiedObject)
{
     foreach (var property in typeof(T).GetProperties().Where(p => !p.GetGetMethod().IsVirtual))
     {
          if (property.GetValue(obj) != null && property.GetValue(modifiedObject) != null)
          {
               if (!(property.GetValue(obj).ToString() == property.GetValue(modifiedObject).ToString()))
               {
                    yield return new KeyValuePair<string, object>(property.Name, property.GetValue(modifiedObject));
               }
          }             
     }
}

Now, it returns the name of the changed property as string and the new value as an object. Now I want to get the original value from the database only against the changed property but the problem is that changed property name is a string. I am calling the method as:

var originalEntity = db.ABCs.AsNoTracking().FirstOrDefault(e => e.Id == v.Id);
var modifiedValues = originalEntity.ModifiedValues<ABC>(t).ToList(); // t holds the modified values of the entity

Let me put this with example:

If my number on a document was 123456 and then I changed it to 456789, the function above will return the property name "PhoneNo" as a string and the new value (456789) as an object. Now I want to query the database for "PhoneNo" property only to get the original value(123456) before writing the new one to database, to maintain a log. Since, I cannot recall any method to query a property name, when the property name is a string type.

How can I do it?





C# Reflection Dynamic Assembly saved as DLL and Referenced assemblies

Assembly A is dynamically generated using reflection, from code located in assembly B which was compiled with Visual Studio. Assembly A is saved as a DLL. Assembly A uses methods from Assembly B.

In Assembly C, I reference both assemblies A and B, but code in A gives errors at runtime about not finding types and methods from B. Assembly C is generated with the CSharp code provider.

I think the solution would be to somehow force Assembly A to load a reference to Assembly B from file before calling any methods or fields from Assembly B, but how to I do that in IL via Reflection.Emit?





C#: Conversion fails between nullable double and int

I have a model, FittingProject, which I'm trying to map to another model, FittingsProjectSharepointModel. Unfortunately FittingProject and FittingsProjectSharepointModel only share values, both property names and types are different.

To ease the mapping process I have created a custom attribute for FittingProject which I use to look up the matching property on FittingsProjectSharepointModel. The problem is that most values fail during conversion, for example going from int to double?.

As you can see by snippet below I have attempt to use the Convert.ChangeType, but it still fails with the same Exception.

public ModelMapper MapModelToFittingsProjectSharepointModel(object model)
{
    if (model == null)
    {
        return null;
    }

    var propertiesWithCustomAttributes = model
        .GetType()
        .GetProperties()
        .Where(p => p.GetCustomAttributes(typeof(SharepointModelPropertyAttribute), true).Length > 0);

    foreach (var prop in propertiesWithCustomAttributes)
    {
        foreach (var customAttribute in prop.GetCustomAttributes(true))
        {
            SharepointModelPropertyAttribute sharePointModelPropertyAttribute = 
                customAttribute as SharepointModelPropertyAttribute;

            PropertyDescriptor sharePointModelprop = TypeDescriptor
                .GetProperties(typeof(FittingsProjectSharepointModel))
                .Find(sharePointModelPropertyAttribute.SharepointModelProperty, false);

            try
            {
                var projectValue = prop.GetValue(model);
                var projectValueConverted = Convert.ChangeType(projectValue, sharePointModelprop.PropertyType);

                sharePointModelprop.SetValue(FittingsProjectSharepointModel, projectValueConverted);
            }
            catch (Exception ex)
            {
                // 
            }


        }
    }
    return this;
}





vendredi 25 septembre 2015

Scala weird behavior for type conversion in generic function

Could anyone explain why that happens?

scala> def as[T](v: Any) = Try(v.asInstanceOf[T])
as: [T](v: Any)scala.util.Try[T]

scala> as[Int]("Hello")
res0: scala.util.Try[Int] = Success(Hello)

scala> res0.map(_ + 1)
res1: scala.util.Try[Int] = Failure(java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer)

It's not about boxing because you could use your own type instead of Int and it behaves the same way.

Doesn't seem to be about by-name parameter either, because you could replace Try with Option and it will be the same.

I'm guessing it's about erasure, but maybe somebody could give a detailed explanation?





Dynamically generate new class objects from different classes

I'm currently writing a simulator for a card game. I'm trying to code a move generator. I have got a base class "Card" from which I'm deriving every card (around 150 different ones). They are pretty specific so I can't implement them within a single class (and I don't want to use any scripting language).

What I need (want) to do: Code 150 classes derived from "Card". Now I need to generate new objects during runtime and push them into my board.

For example:

std::vector<Card*> board;
board.push_back(new Card132());

So how would I be able to do this - cause I need to decide during runtime which object (from which class) I need to generate?

Thanks in advance.





What does it mean to "mark a field as literal" in the world of .NET?

According to Microsoft's documentation, Type.GetValue(object) will throw a NotSupportedException if "A field is marked literal, but the field does not have one of the accepted literal types."

I have no idea what it means to "mark a field as literal." I want to understand this so that I may know how to guard against this exception.





Why property "does not exist" when do exist?

Using PHPUnit and building on Jenkins, this is the message that I got:

1) MyClassTest::testIsPropertyExist with data set #1 ('_table_usage') ReflectionException: Property _table_usage does not exist

When my test is:

/**
 * @dataProvider testIsPropertyExistDataProvider
 */
public function testReflectionClassIdtTransactionProperty($property)
{
    $object = new MyClass();
    $class = PHPUnitReflectionClass::getInstance($object);
    $response = $class->getProperty($property);
    $this->assertTrue(is_int($response) || is_bool($response));
}

public function testIsPropertyExistDataProvider() {
    return array(
        array('_idt'),
        array('_table_usage')
    );
}

And my class:

class MyClass
{
    private $_idt;
    private $_table_usage;

    public function __construct()
    {
        $this->_table_usage = false;
        $this->_idt = 1;
    }
}

So, i've been using the...

$class = PHPUnitReflectionClass::getInstance($object);
$response = $class->getProperty($property);

... in other tests, and having no problem.

So my doubts is, what am I missing and why the "_idt" exist?





Get a generic class field type with Java Reflections

I have the following class structure:

public class GenClass<T> {
    public T elem;
}

I use it in the following way:

public class Test {
    public GenClass<UUID> data;

Now I want to get the type of elem using the Field object of data(Test.class.getField("data")) But when I use getType to retrieve the class the Generic information is stripped away.

How can I map the generic Information from getGenericType to the class object to retrieve the field with a correct type?





Java Reflections: Get Classes but not SubTypes

I'm upgrading from org.reflections:reflections:0.9.5 to version 0.9.9. I am using:

Reflections reflectionPaths = new Reflections("resources", new TypeAnnotationsScanner());
Set<Class<?>> rootResourceClasses = reflectionPaths.getTypesAnnotatedWith(Path.class);

Which gets me all classes in the resources package with an @Path Annotation. Since the library has been updated the top line requires an extra new SubTypesScanner() for the code to run. I however do not want sub types to be returned.

How can I use this new version of the library to pull back only classes and interfaces that are not sub types?





Does sonarQube detects the unused methods called by reflection api

We are using sonarQube tool, which detects unused methods in the project. We have used java.lang.reflection api's to create/invoke the methods. The detected methods are really not used by reflection apis' or does it detects only the manual invocation of methods?





How add/update data in db with reflection

I would like to save/update my changes in db with reflection. I just have name of a table and the id pk of the field. I try to update this table with reflection...

 var table =(IQueryable)dbContext.ctx.GetType().GetProperty(tableName).GetValue(dbContext.ctx, null);

First I have the table and with the Iqueryable I don't know how I can update my table in db.

Any help?

Thx





How to get the MethodInfo for Enumerable.SequenceEqual

I'm trying to get the MethodInfo for Enumerable.SequenceEqual, using Type.GetMethod(...). So far I have tried the following:

var mi = typeof(Enumerable).GetMethod(nameof(Enumerable.SequenceEqual),
    BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any,
    new Type[] { typeof(IEnumerable<>), typeof(IEnumerable<>) }, null);

and

var enumTyped = typeof(IEnumerable<>).MakeGenericType(ValueType);
var mi = typeof(Enumerable).GetMethod(nameof(Enumerable.SequenceEqual),
    BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any,
    new Type[] { enumTyped, enumTyped }, null);

However, both solutions return null instead of the method I want. I know the method is retrievable by calling GetMethods() and filtering, but I'd very much like to know how to retrieve it using GetMethod(...).





jeudi 24 septembre 2015

Ray Tracing Reflection,Reflecting the on the wrong side

Hey i am currently writing a ray tracer and i am try to add reflections. I have two questions.Is my ray direction calculation correct because it does not seem wrong.My second question is how would i implement reflections because this is not working to good.

Reflections

It seems like the reflections are reversed.

Here is my code For Trace!

public class Tracer {

public boolean Tracing;
public Camera Cam;
public int Width, Height;
public BufferedImage Image;
public Color BackGroundColor;
public int StartX, StartY, EndX, EndY,RowCount,ColCount;
public double AmbientLight;
public double DiffuseLight;
public int MaxReflectionCount;
public ArrayList<GeometricObject> GeoObjects;
public ArrayList<LightObject> LightObjects;

public Tracer(Camera cam, int width, int height, BufferedImage image, Color backGroundColor, int startX, int startY, int endX, int endY, int rowCount, int colCount, double ambientLight, double diffuseLight, int maxReflectionCount, ArrayList<GeometricObject> geoObjects, ArrayList<LightObject> lightObjects) {
    super();
    Cam = cam;
    Width = width;
    Height = height;
    Image = image;
    BackGroundColor = backGroundColor;
    StartX = startX;
    StartY = startY;
    EndX = endX;
    EndY = endY;
    RowCount = rowCount;
    ColCount = colCount;
    AmbientLight = ambientLight;
    DiffuseLight = diffuseLight;
    MaxReflectionCount = maxReflectionCount;
    GeoObjects = geoObjects;
    LightObjects = lightObjects;
}

public void TracePixelFast(int x, int y) {
    Color color = new Color(BackGroundColor.r,BackGroundColor.g,BackGroundColor.b);
    for(int o = 0;o < GeoObjects.size();o++){
        GeometricObject GO = GeoObjects.get(o);
        Ray r = new Ray(Cam.GetRayPos(Width, Height, x, y, 1, 1, RowCount, ColCount), Cam.GetRayDir(Width, Height, x, y, 1,1, RowCount, ColCount));
        double hit = GO.hit(r);
        if (hit != 0.0) {
            color = Cal_Pixel(x,y);
            Image.setRGB(x, y, color.toInt());
            break;
        }
    }
}

public void TracePixelSmooth(int x, int y) {
    Image.setRGB(x, y,Cal_Pixel(x,y).toInt());
}

public Color Cal_Pixel(int x,int y){
    Color color = new Color(BackGroundColor);
    Color colorh = new Color(BackGroundColor);
    Color bgc = new Color(BackGroundColor);
    int HIT = 0;
    int MISS = 0;
    for (int row = 0; row < RowCount; row++) {
        for (int col = 0; col < ColCount; col++) {
            double min = Double.MAX_VALUE;
            Ray r = new Ray(Cam.GetRayPos(Width, Height, x, y, row, col, RowCount, ColCount),Cam.GetRayDir(Width, Height, x, y, row, col, RowCount, ColCount));
            for (int o = 0; o < GeoObjects.size(); o++) {
                GeometricObject GO = GeoObjects.get(o);
                double hit = GO.hit(r);
                if (hit != 0.0 && hit < min) {
                    min = hit;
                    colorh = ShadePixel(0,GO, r, hit);
                    HIT++;
                } else {
                    double min2 = Double.MAX_VALUE;
                    for (int o2 = 0; o2 < GeoObjects.size(); o2++) {
                        if(o!=o2){
                        GeometricObject GO2 = GeoObjects.get(o2);
                        double hit2 = GO2.hit(r);
                        if (hit2 != 0.0 && hit2 < min2) {
                        min2 = hit2;
                        bgc = ShadePixel(0,GO2, r, hit2);
                        }
                     }
                    }
                    MISS++;
                }
            }
        }
    }
    for(int h = 0;h < HIT;h++){
        color.Add(colorh);
    }
    for(int m = 0;m < MISS;m++){
        color.Add(bgc);
    }
    color.Divide(RowCount * ColCount);
    return color;
}

public Color ShadePixel(int ReflectionDepthCount,GeometricObject GO,Ray ray,double t){
    Normal normal = GO.Cal_Normal(ray, t);
    if(GO.Reflectivity > 0){
    Color GoColor = new Color(Cal_Reflection(GO,ReflectionDepthCount, ray, normal));
    Color finalcolor = new Color(Cal_Light(GoColor, normal));
    return finalcolor;
    }else{;
        Color finalcolor = new Color(Cal_Light(GO.Color, normal));
        return finalcolor;  
    }
}

public Color ShadePixel_End(GeometricObject GO,Normal normal){
    Color GoColor = new Color(GO.Color);
    Color finalcolor = new Color(Cal_Light(GoColor, normal));
    return finalcolor;
}

public Color Cal_Light(Color color,Normal normal){
    ArrayList<Color> PixelShade = new ArrayList<Color>();
    Color Final = new Color();
    for(int l = 0;l < LightObjects.size();l++){
        LightObject light = LightObjects.get(l);
        Vector3D r_Dir = light.Pos.Sub(normal.Origin);
        r_Dir.normalize();
        Ray raytolight = new Ray(normal.Origin,r_Dir);
        int WAS_HIT = 0;
        for(int o = 0;o < GeoObjects.size();o++){
            GeometricObject NGO = GeoObjects.get(o);
            double hit = NGO.hit(raytolight);
            if (hit != 0.0) {
               WAS_HIT = 1;
            }
        }
        PixelShade.add(light.ShadePixel(WAS_HIT, normal, r_Dir, color, AmbientLight, DiffuseLight));
    }
    for(int s = 0;s < PixelShade.size();s++){
        Final.Add(PixelShade.get(s));
    }
    Final.Divide(PixelShade.size());
    return Final;
}

  public Color Cal_Reflection(GeometricObject OriginalObject,int ReflectionDepthCount,Ray InRay,Normal normal){
    if(ReflectionDepthCount <= MaxReflectionCount){
        GeometricObject LastGO  = null;
        Ray LastRay = null;
        double LastT = 0.0;
        double min = Double.MAX_VALUE;
        double Dir_Out_Dot = InRay.Direction.Dot(normal.Direction);
        Vector3D Dir_Out = normal.Direction.Mul(2).Mul(Dir_Out_Dot).Sub(InRay.Direction);
        Ray r = new Ray(normal.Origin,Dir_Out);
        for (int o = 0; o < GeoObjects.size(); o++) {
            GeometricObject GO = GeoObjects.get(o);
            double hit = GO.hit(r);
            if (hit != 0.0 && hit < min) {
                min = hit;
                LastGO = GO;
                LastRay = r;
                LastT = hit;
            }
       }

        if(LastGO != null){
            Color Reflected = new Color(ShadePixel(ReflectionDepthCount, LastGO,LastRay, LastT));
            Color HitColor = new Color(LastGO.Color);
            Color FinalColor = new Color();
            Reflected.Mul(OriginalObject.Reflectivity);
            FinalColor.Add(HitColor);
            FinalColor.Add(Reflected);
            FinalColor.Divide(2);
            FinalColor.Add(OriginalObject.Color);
            FinalColor.Divide(2);
            return FinalColor;
        }
    }
    return OriginalObject.Color;
}

public void TraceArea(boolean SmoothTracing) {
    Tracing = true;
    if(SmoothTracing){
        for (int x = StartX; x < EndX; x++) {
            for (int y = StartY; y < EndY; y++) {
                TracePixelSmooth(x,y);
            }
        }
    }else{
        for (int x = StartX; x < EndX; x++) {
            for (int y = StartY; y < EndY; y++) {
                TracePixelFast(x,y);
            }
        }
    }
}

}

This is my code for my Sphere.

public class Sphere extends GeometricObject{

public Vector3D Center;
public double Radius;

public Sphere(Vector3D Center,Color Color,double Radius,double Reflectivity){
    this.Center = Center;
    this.Radius = Radius;
    this.Color = Color;
    this.Reflectivity = Reflectivity;
}

public double hit(Ray ray) {
    double a = ray.Direction.Dot(ray.Direction);
    double b = 2 * ray.Origin.Sub(Center).Dot(ray.Direction);
    double c = ray.Origin.Sub(Center).Dot(ray.Origin.Sub(Center))-Radius*Radius;
    double discreminant = b*b-4*a*c;
    if(discreminant < 0.0f){
        return 0.0;
    }else{
        double t = (-b - Math.sqrt(discreminant))/(2*a);
        if(t > 10E-9){
            return t;
        }else{
            return 0.0;
        }
    }
}

public Normal Cal_Normal(Ray ray,double t) {
    Vector3D NPos = new Vector3D(ray.Origin.x + ray.Direction.x*t,ray.Origin.y + ray.Direction.y*t,ray.Origin.z + ray.Direction.z*t);
    Vector3D NDir = NPos.Sub(Center).Div(Radius);
    return new Normal(NPos,NDir);
}

}

If you need more of my code just request it and i will upload it. And if you want to help me improve me reflection part of my ray tracer i would like it to look more like this.Only if you wish to pour you knowledge of ray tracing onto my poor broken soul!

Picture Of Hope





Reflections library returns empty list in Android

I'm attempting to retrieve a list of classes with a specific annotation in Android. I'm trying to use the Reflections library to do so. But no matter what I do, Reflections returns an empty set. Finally, I tried using Reflections.getAllTypes(), which should return all classes in a package, and it gives me the message "Couldn't find subtypes of Object. Make sure SubTypesScanner initialized to include Object class - new SubTypesScanner(false)" I have verified that I am doing so, so I looked in the code for that method and it returns that error if there are no classes in the package.

Here's an example of the code where I'm getting the error:

Reflections reflections = new Reflections(this.getClass().getPackage().getName(), 
        new SubTypesScanner(false));
Set<String> classes = reflections.getAllTypes(); // Throws runtime error

This should, at the very least, return the class that it is called from. I've also tried using an empty string for the package, and the answer here. Any ideas what could be causing this?





Creating dynamic proxy class from "object representation"

Is it possible to create an object model representation of an actual class that can be turned into a real class again which fits the signature of the origin for using it as some sort of dynamic proxy?

Currently, I've got a plugin API / interfaces inside my application which looks like this (simplified dummy):

public interface IPlugin {
    void Initialize();
    void SendData(DataObject data);
}

A DataObject could look like this:

public class DataObject {
    public string Value1 { get; set; }
    public string Value2 { get; set; }
}

With this interface, I can send whatever kind of data I like to a plugin, however it has a few drawbacks:

  • It's not really extensible
  • The plugin needs to manually parse/interpret the data
  • I can send complete gibberish to the plugin
  • I need an additional specification to specifiy how the data has to look like.

What I'd like to have is a plugin interface that could be extended like this:

public interface IPlugin :
    ICanReceive<ArbitaryClass1>,
    ICanReceive<ArbitaryClass2>
{
    // implements void Receive(ArbitaryClass1 value);
    // implements void Receive(ArbtiaryClass2 value);
}

The plugin would provide the classes itself without having the main application to know about these types. In order to make this work, I thought about the following:

  • Reflect the generic parameters of the interfaces the plugin implements
  • Map the types into a "object model", which could look like this:

Example

interface IType {
    + TypeKind (e.g. primitive, structured, reference, collection)
}

interface IStructuredType : IType {
    + collection of <IPropertyType>
    + StructuredTypeKind (e.g. complex, entity)
}

  • Persist the object model in a database for value editing
  • Upon sending the data to the plugin, create proxy classes out of the object model with the same signature that was originally reflected from the types, thus matching the methods of ICanReceive<'T>

My question is: How could such a thing work (especially the dynamic proxy stuff)? How could this be done? Reflection.Emit? CodeDOM? There are already certain standards to represent an object model, such as EDM (used in EntityFramework, OData) and AFAIK, Entity Framework already returns dynamic proxy objects for stuff like lazy loading when accessing entities from a DbSet<'T>, so there must be a way to do this. :)





Compare open generic parameter with open generic interface type

Is it possible (in c#) to compare an open generic parameter e.g. T in:

public void CompareMethod<T>() { ... }

with the type of an open generic interface (or class)?
Here is an example interface:

public interface IExample<T> { }

And then somehow inside the method compare them like this:

public void CompareMethod<T>()
{
    if (typeof(IExample<>) == typeof(T))
    {
        //execute
    }
}

The if body won't execute when called the method like this:

CompareMethod<IExample<object>>();

It is important that I don't know in advance what closed types will be entered in the open generic parameter of the CompareMethod.





Retrieve the field name in the parent message with a field descriptor using Protocol Buffers

Is it possible with Google Protocol Buffers to retrieve the field name (not the field type) of the parent message by using descriptors in C++?

Consider the following minimal example:

message MessageHeader {
  string addressee = 1;
}

message Message {
  MessageHeader header = 1;
}

I want to retrieve the string "header.addresse" with the following function:

std::string createFieldQueryFrom(
    const google::protobuf::FieldDescriptor* const descriptor)
{
  // TODO(wolters): The descriptor for the containing FIELD is required. Is
  // there a way to retrieve it?
  //
  // containing_descriptor->name() returns "Message", what I want is
  // "header"!
  const google::protobuf::Descriptor* containing_descriptor{
      descriptor->containing_type()};

  // TODO(wolters): Add recursion if able to get the actual attribute name of
  // the containing FIELD.

  return "";
}

  1. Is this possible, or doesn't a google::protobuf::FieldDescriptor instance provide the information required to fulfil that task?
  2. If the answer to 1. is no: Is this possible at all (if so, can you provide me an example)?




Entity framework know "not null" by reflection

I need to know if my column in my database is set as "not null" or "nullable" by reflection.

I try with with this line :

bool canBeNull = !col.PropertyType.IsValueType || (Nullable.GetUnderlyingType(col.PropertyType) != null);

But my boolean is always true. Also when column are set as "not null".

What is the best way for know this information?

Thx





mercredi 23 septembre 2015

Java Reflection Method Invocation with Unknown Bean Structure

I have written some code that feels like a hack.

    private void handleSpecialCase(Method mvw, InterfacePersistenceBean pObj, AbstractBeanWrapper wrapper, String methodCore)
        throws TestStructureException
    {
       try
      {

        Parameter p= getParameterByName(methodCore, this.PREFIX_SET,pObj);
        Method mp=null;
        try
        {
             mp = pObj.getClass().getMethod("set"+methodCore, new Class[]
            { p.getType() });
        }
        catch(NoSuchMethodException e)
        {
             mp = pObj.getClass().getDeclaredMethod("set"+methodCore, new Class[]
                        { p.getType() });
        }

        Method serviceMethod = beanByIdService.getClass().getMethod("get"+methodCore, new Class[]
                { java.lang.Long.class });

        InterfacePersistenceBean beanToSet=(InterfacePersistenceBean)serviceMethod.invoke(beanByIdService, mvw.invoke(wrapper));
        mp.setAccessible(true);
        mp.invoke(pObj, beanToSet);
    }
    catch (Exception e)
    {
        SS.getLogger().error(e.getMessage()+" "+e.getCause(),e);
        throw new TestStructureException(e.getMessage(), e.getStackTrace());
    }

  • The inner try block (i.e., getMethod() ) will get methods from superclasses, but will not get protected or private methods. If a method is protected it throws NoSuchMethodException.

  • Hence the inner catch block uses getDeclaredMethod() which will get protected and private methods but throw NoSuchMethodException on superclass methods.

  • A protected/private superclass method would always throw an exception here which is fine for my purposes but nonetheless inelegant.

Can someone suggest a more flexible, robust, and elegant approach (preferably without using annotations)?

Thanks a million





Scala: inferring a type parameter from class name

Here is what I am trying to do -

val classType = someMagicCode("com.mydomain.SomeClass")
someMethod[classType](someArgs)

Is it possible to do this in Scala? If yes, how?





In Scala how can I reflect on a typedef (eg. type Data = Map[String,Any])?

I'm writing some reflection code. I have a class like this:

case class Foo(
   info : Map[String,Any]
)

I reflect on this class like this:

ctor.typeSignature.paramLists.head.map( f => {
   println("F: "+f.typeSignature)
})

When defined as above I see what I expect for the type of member info: Map[String,scala.Any]

But... if I do this:

type Data = Map[String,Any]
case class Foo(
   info : Data
)

Now I see the type of info as: co.blocke.scalajack.test.v4.Data

How can I tell if a type like Data above is actually a typedef any how can I see what it resolves to? (the type of 'f' in the clip above is universe.Symbol)

I mistakenly thought it was compiler-candy and after compilation it would have resolved to its defined type, but apparently not!





C# mutantion testing - change method runtime with il code

You can skip to my approach if you don't mind what I'm actually trying to do.

What I'm trying to do
Hey I'm trying to make mutant testing,
inspired by the talk
http://ift.tt/1iMb6qv

But I'm using c# and the best mutant libraries are made in java such as
http://pitest.org/

There are some frameworks for c# such as ninjaturtles and visualmutator, but they both doesn't work in my computer for some reason(I get a weird error). and also I thought it would be interesting creating my own.

About mutant testing
For those who doesn't know what is mutant testing, it's a testing for the tests, most people use code coverage to check that their test cover all the scenarios, but it's not enough, cause just because it gets to a piece of code doesn't mean it tests it. It changes a piece of code, and if the tests still pass it means you didn't tested the piece of code.

My approach
So I've tried starting with a simple code that gets the il codes of a method.

        var classType = typeof(MethodClass);
        var methodInfo = classType.GetMethod("ExecuteMethod", BindingFlags.NonPublic | BindingFlags.Static);

        byte[] ilCodes = methodInfo.GetMethodBody().GetILAsByteArray();

this is the MethodClass I'm trying to change:

public class MethodClass
{
    private static int ExecuteMethod()
    {
        var i = 0;
        i += 5;
        if (i >= 5)
        {
            i = 2;
        }
        return i;
    }
}

now I'm trying to replace the ils

        for (int i = 0; i < ilCodes.Length; i++)
        {
            if (ilCodes[i] == OpCodes.Add.Value)
            {
                ilCodes[i] = (byte)OpCodes.Sub.Value;
            }
        }

but then I'm not sure how to update my function to work with the new il codes.

I've tried using

        var dynamicFunction = new DynamicMethod("newmethod", typeof(int), null);
        var ilGenerator = dynamicFunction.GetILGenerator();

and then the il generator has a function emit, that gets operator and value, so I could use this. but I don't have the value to put in the emit..

Does anybody know how to do it?





Jackson ReadValue doesn't convert to List<>

I have a problem. I work with custom annotation, which takes method params and converts them from json to pojo. Here is example:

...
MethodParameter param 
// here a parameter from methods, marked with custom annotation
...
JSON_MAPPER.readValue(node, param.getParameterType());

java.util.LinkedHashMap cannot be cast to com.liferay.portal.kernel.util.KeyValuePair

But when I try to convert List<> it doesn't work. But the code below works fine

JSON_MAPPER.readValue(node, new TypeReference<List<KeyValuePair>>(){});

how I can figure out the type of income data? What should I do?





Get type of enum in .NET class

Consider the following C# class declaration:

public class MyClass {
    private enum Colours { Red, Green, Blue }
}

Which is sat in a separate class library/DLL.

Given just the typeof(MyClass) object (System.Type), is there any way to check if the class contains an enum called Colours at runtime and if so return it's corresponding System.Type object?

What I'm trying to do is write some generic code that's given the type of a class and determine if contains a specifically named enum inside and then query the values in the enum.

I know how to use Reflection to query things like GetFields, GetProperties etc. but there isn't a GetClasses or GetEnums method in System.Type.

I suspect this kind of information is in the assembly?





Dynamic proxy with custom methods

I am trying to write a generic wrapper for javax.sql.DataSource instance. My problem is that this class is configured by calling setters on the implementation - in configuration I get some properties with foo=bar and then setFoo("bar") is called on the data source. These setters are not invoked using interface calls but using reflection.

Now, when I want to wrap an implementation, I cannot know until runtime what setters it has. I would need a java.lang.reflect.Proxy that would, in its getClass().getMethods() return my own set of methods, not just those that are defined in the interfaces.

One way I can see is use Javassist and generate a custom interface whose methods would match setters on the instance of DataSource I got, and then provide this interface to the proxy factory method. Is there any pure Java rt.jar way to achieve the above, without additional dependencies (to Javassist or CGLib or ...)?





Exception has been thrown by the target of an invocation (MethodBase.Invoke Method)

I want to catch the exceptions that are thrown in methods called with invoke method.

public void TestMethod()
{
   try     
   {
       method.Invoke(commandHandler, new[] { newCommand });
   }
   catch(Exception e)
   {     
       ExceptionService.SendException(e);
   }
}

method.Invoke calls the following method:

public void Register(/*parameters*/)
{
     if(test_condition())
          throw new CustomException("Exception Message");
}

The problem is that when I catch the CustomException, in the TestMethod, the e variable on the catch statement has NOT the type CustomException. It has the following message: "Exception has been thrown by the target of an invocation".

I want to catch the exception that has been raised (which is CustomException), and pass it to the ExceptionService mechanism.

What am I doing wrong?





java reflection invoke setter with Object type parameter

I am quite new in java. Please help me to find the way to invoke method with an Object parameter.

Here's my sample code:

public class Myclass {

private Foo foo;
private Bar bar;

public void setFoo(Foo foo) {
   this.foo = foo
}

public void setBar(Bar bar) {
   this.bar = bar
}

I tried to used jackson library to convert from HashMap to MyClass. But It didn't work for me.

ObjectMapper mapper = new ObjectMapper();
mapper.convertValue(myHashMap, MyClass);`            // jackson library

But it still couldn't parse Date, Long And other Specific classes.

Then I change the way to do it by myself using reflection.

final Map<String, Method[]> methods = new HashMap<String, Method[]>();
for (PropertyDescriptor pd : Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors()) {
    methods.put(pd.getName(), new Method[]{ pd.getReadMethod(), pd.getWriteMethod()});
}

...

public void putAll(HashMap<String, Object> map, Object object) {
    Iterator it = map.keyset().iterator();
    while(it.hasNext()) {
        String key = (String) it.next();
        Method[] m = methods.get(key);
        m[1].invoke(object, map.get(key));          // Error here.
    }
}

With this code. I have exception with argument mismatch. How do I solve this ? Or the only way I have to do is get the parameter type to check and cast every object to match the setter ?

Thank in advance.





Python2 reflection: Strange behavior of __import__()

I need to have a generic script which takes some_module.function as argument and executes it. I wrote a solution for this (has to be Python-2.4 compatible...):

def get_function(f_name):
    """Return function from library..."""
    lib, f = f_name.rsplit('.', 1)
    module = getattr(__import__(lib), lib.rsplit('.', 1)[-1])
    return getattr(module, f)

f = get_function('my_libs.testlib.test_function')
# finally, this executes the function
f()

My question is:

Why do I have to do the getattr() after __import__()?

Turns out module = __import__('lib') will have the namespace above the one of lib.

So when I wanted to call a function from lib, say lib.f_x, I would have to do it like:

module = __import__('lib')
module.lib.f_x()

instead of what I would expect:

module = __import__('lib')
module.f_x()

Or use the contruct with getattr() as above. Why is that?





mardi 22 septembre 2015

Retrieving original class types from anonymous classes

Given a class with an empty constructor and a var:

class MyClass() {
  var myVar: Int = 0
}

When the class is instantiated with a closure, this yields an object with the underlying type of an anonymous class rather than MyClass:

// getClass yields type my.package.MainClass$$anonfun$1$anonfun$apply...
val myNewClassInstance: MyClass = new MyClass() { myVar = 2}

Is it possible to retrieve the original class type MyClass using reflection and the object myNewClassInstance, in order to create new object instances from it?





C# Reflection - find first method in the stacktrace that wasn't part of the consructor for this object

I am trying to use reflection to find the location that an object is being constructed from. I want my code to go in the base class constructor, but it to be able to work out the first method that wasn't part of constructing this object.

class A
{
     public A()
     {
     // reflection goes here
     }
}

class B : A
{
     public B()
     {
     }
}

class C
{
     B b = new B()
}

So here I would like to get back that the B object is being constructed in the constructor of C. (I just need a text representation for some debugging purposes; this is only for debug builds so I don't need to worry about release builds)

So far I have:

var stacktrace = new StackTrace()
var i = 0;
while(stackTrace.GetFrame(i).GetMethod().IsConstructor)
{
    i++
}

This works correctly anywhere that B is being constructed in a standard method - however when (as in the example above) B is being constructed in Cs constructor, it keeps going up the chain.

An option is to check whether method.DeclaringType is an A, which works - except for ideally I could also cope with the case where C inherits from A.

Any other suggestions?





Get an inner class via reflection (Windows 8.1)

I have a class called Languages. It contains several other static classes. For instance:

namespace TryReflection
{
    class Languages
    {
        public static class it
        {
            public static string PLAY = "Gioca";
            public static string START = "Inizia!";
            public static string NEXT = "Prossimo";
            public static string STOP = "Ferma!";
            public static string SCORE = "Punti";
            public static string RESTART = "Per cambiare la difficoltà inizia una nova partita";
        }

        public static class en
        {
            public static string PLAY = "Play";
            public static string START = "Start!";
            public static string NEXT = "Next";
            public static string STOP = "Stop!";
            public static string SCORE = "Score";
            public static string RESTART = "To change difficulty restart your match";
        }
    }
}

Each class contains some static strings. I'd like to access these classes via reflection (and with the system language string that I have). I can access the Languages class this way:

Type tt = Type.GetType("TryReflection.Languages", true); 

And then I'd like to do something like:

tt.GetNestedType();

Unfortunately, it seems that on Windows 8.1 there's no GetNestedTypes method. So, how can I access one of these classes? Thank you.





How do I assign method name (or annotation element) strings in a way that is safe for refactoring?

Suppose I have a class com.example.Foo and another class com.sample.Bar which needs to know the fully-qualified name of Foo. If I am a Java novice I might put:

public class Bar {
    private String fooName = "com.example.Foo";
    //...
}

However, if I refactored Foo to change the name or package, the changes would not be reflected in Bar, unless the IDE is really clever. So it's better to do something like this:

import com.example.Foo;

public class Bar {
    private String fooName = Foo.class.getName();
    // ...
}

This way, if I refactor Foo, then the change should be picked up by Bar.

Now consider methods. If I have a method name in class Foo and the name needs to be known by Bar, it seems the best I can do is:

public class Bar {
    private String bazName = Foo.class.getMethod("bazMethod", Qux.class);
    // ...
}

But I haven't actually achieved anything - I still have a string literal "bazMethod" which won't be refactored if the real bazMethod gets renamed.

What I really want to do is something like:

public class Bar {
    private String bazName = tellMeTheMethodName((new Foo()).bazMethod(null));
    // ...
}

Not sure if this is possible somehow and if there is any way around it.

Now comes the real problem - even if you can sort that out as above, the real thing I am trying to access is an annotation attribute/element name. But annotations are abstract and cannot even be instantiated. So is this possible?





Use property Created by Property Info and use in Lmabda

I have a method with parameter as object, the object is a string value of properties in DocumentModel Class

 private PropertyInfo SortingListView(object obj)
 {
     return typeof(DocumentModel).GetProperty(obj.ToString());
 }

I want the PropertyInfo to be used in a lambda expression like below,

 var SortedDocuments=Documents.OrderByDescending(x => SortingListView(obj));

But its not working. Any suggestions ? or any better way ? please help.





Get caller class and method name

I am trying to get the caller class and method name inside a function in a Scala app. I am currently making use of the stack trace, but the performance has decreased. I am doing something like

stackTrace(CodeDepth).getClassName
stackTrace(CodeDepth).getMethodName

I have found the Java reflection to be a lot more faster, but i can only get the class name with

sun.reflect.Reflection.getCallerClass(CodeDepth).getName()

Is there a way to get the method name (and optionally the line number) via reflection? Maybe using Scala's reflection?

Thanks





Call a method passed as parameter on an object passed as parameter

I have a class defining several functions with the same signature

public class MyClass
{
    public string MyParam1() ...
    public string MyParam2() ...
    ...
}

From another class I want to call a method passed as parameter on an object passed as parameter

void MyFunction(MyClass anObject, Func<string> aMethod)
{
    string val = ??? // Here call aMethod on anObject
}

I'm pretty sure it's possible to do this using reflection, but is there a not to difficult way to do it ?

In fact I have a set of objects, not a single object, it's why I cannot call directly the method of the object.





Set private field value with reflection

I have 2 classes: Father and Child

public class Father implements Serializable, JSONInterface {

    private String a_field;

    //setter and getter here

}

public class Child extends Father {
    //empty class
}

With reflection I want to set a_field in Child class:

Class<?> clazz = Class.forName("Child");
Object cc = clazz.newInstance();

Field f1 = cc.getClass().getField("a_field");
f1.set(cc, "reflecting on life");
String str1 = (String) f1.get(cc.getClass());
System.out.println("field: " + str1);

but I have an exception:

Exception in thread "main" java.lang.NoSuchFieldException: a_field

But if I try:

Child child = new Child();
child.setA_field("123");

it works.

Using setter method I have same problem:

method = cc.getClass().getMethod("setA_field");
method.invoke(cc, new Object[] { "aaaaaaaaaaaaaa" });





dalvik Java How to call super class method using reflect?

I my case: I want to override a hide method in TextView by extends TextView, and make call to its super method.

public class MyTextView extends TextView {
    protected void makeNewLayout(int wantWidth, int hintWidth,
                                 BoringLayout.Metrics boring,
                                 BoringLayout.Metrics hintBoring,
                                 int ellipsisWidth, boolean bringIntoView) {
        // omit try catch for simple
        Method method = Class.forName("android.widget.TextView").getDeclaredMethod("makeNewLayout", int.class, int.class, BoringLayout.Metrics.class, BoringLayout.Metrics.class, int.class, boolean.class);
        method.setAccessible(true);
        method.invoke(this, wantWidth, hintWidth, boring, hintBoring, ellipsisWidth, bringIntoView);
    }
}

The problem is my self define makeNewLayout is called and the method.invoke is executed, but the method invoke is MyTextView::makeNewLayout not TextView::makeNewLayout, it a dead recursive call.

How can I acheive it?

PS: makeNewLayout is a hide function, so I cannot call it directly by super.makeNewLayout(...)





C# down-cast ComponentRegistration to non-generic type

I`m using Castle.Windsor library, and what i want is to get "Implementation" property, from all items in IRegistration[].

I have following interfaces and classes:

public interface IA
  {
    int a { get; set; }
  }

  public class A : IA
  {
    public int a { get; set; }
  }

  public interface IB
  {
    int b { get; set; }
  }

  public class B : IB
  {
    public int b { get; set; }
  }

And a static class which contains this Components:

  public static class Bootekstraperek
  {
    private static readonly IRegistration[] _commonRegistrations =
    {
      Component.For<IA>().ImplementedBy<A>(),
      Component.For<IB>().ImplementedBy<B>()
    };

    public static void Test()
    {
      List<IRegistration> list = _commonRegistrations.ToList();

      foreach (var registration in list)
      {
        ComponentRegistration a = registration as ComponentRegistration;
        Console.WriteLine(a.Implementation.FullName);
      }
    }
  }

And of course variable a is null after every iteration. It works only when i cast to Generic ComponentRegistration

var a = registration as ComponentRegistration<A>;

But, that dont helps me if i have too much different components inside this array. So Switch statement is not an option. I have tried using reflections, but i still didn`t managed to properly cast.

How can i achieve what i want With or Without using reflections?

thxia.





lundi 21 septembre 2015

Cannot test a class that return a customException

While experimenting JUnit, I am trying to test a simple private method as follows, this method receives a String and make sure it does not include the word 'Dummy' in it.

private void validateString(String myString) throws CustomException {

    if (myString.toLowerCase().matches(".*dummy.*"))
        throw new CustomException("String has the invalid word!");

}

I am trying to access the private method through reflection but the test fails! It shows following exception:

java.lang.AssertionError:Expected test to throw
(an instance of com.myproject.exception.CustomException and exception 
with message a string containing "String has the invalid word!")

Based on answer of this question, I am catching InvocationTargetException as well.

JUnit

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void shouldThrowExceptionForInvalidString() {

        thrown.expect(CustomException.class);
        thrown.expectMessage("String has the invalid word!");

        try {
            MyClass myCls = new MyClass();
            Method valStr = myCls.getClass().getDeclaredMethod(
                    "validateString", String.class);
            valStr.setAccessible(true);
            valStr.invoke(myCls, "This is theDummyWord find it if you can.");
        } catch (InvocationTargetException | NoSuchMethodException
                | SecurityException | IllegalAccessException
                | IllegalArgumentException n) {
            if (n.getCause().getClass() == CustomException.class) {
                throw new CustomException("String has the invalid word!");
            }
        }

    }





Call non-abstract method of abstract class without its instance

Consider this code:

public interface IRegistryClass
{
    public IRegistryClass get();
}

public abstract class Skill implements IRegistryClass
{
    @Override
    public Skill get()
    {
        return new SkillFake();
    }

    private final class SkillFake extends Skill
    {}
}

Would it be possible to call skill#get() when being ONLY supplied with Skill.class?

Regular Java won't allow to class#newInstance() abstract classes. Question is: Is there a way?

Note: I can't have static keyword. I need inheritance on this one.





Serialize Base Class Implementation for all "new" Properties

I have a bunch of classes that were auto-generated from an XSD, and provided to me in a compiled DLL for which I don't have the source code. I have a need to add interfaces to each of the types, which resulted in code such as the following:

public interface IBar
{
    string SomeProperty { get; set; }
}

public interface IFoo<TBar> where TBar : IBar
{
    TBar Bar { get; set; }
}

[XmlType(Namespace = "SomeNamespace", TypeName = "bar")]
public class BarWrapper : BarFromXSD, IBar
{
}

[XmlType(Namespace = "SomeNamespace", TypeName = "foo")]
public class FooWrapper : FooFromXSD, IFoo<BarWrapper>
{
    [XmlElement("bar")]
    public new BarWrapper Bar
    {
        get { return base.Bar as BarWrapper; }
        set { base.Bar = value; }
    }
}

If the client gives me a DLL where any of the interfaces to the underlying types changes, I will get compile-time errors telling me such. However, that is NOT true if the serialization attributes change in the underlying DLL. In that case, my wrapper classes will happily serialize into objects that are incompatible with the associated XSDs.

To avoid this issue, I would like to do the simpler of either:

1) Override default serialization, in order to ignore the "new" property implementations, or
2) Reflectively copy all XML serialization attributes from the base class to the derived class

The issues that I am trying to address with any potential solution are:

1) I would like to perform reflection once, in the static constructor, to determine the serialized element/attribute names and namespaces.
2) I have multiple classes that follow the same pattern as FooWrapper, so any solution should would work for any such classes.
3) The classes that follow the FooWrapper pattern can contain other properties not defined in the base class that require serialization.
4) The ideal solution should gracefully handle new properties. For example, if at a later time I add or remove a "new" property, I shouldn't have to add/remove other methods, or have to hard-code the name of the "new" property in the static constructor.

Any insight to a solution that meets these requirements is greatly appreciated.





propertinfo.getvalue() not giving expected result

I'm trying to check if webcontrol supports a particulat property - if it does I want to check if a value exists - if a value exists, I want to do nothing, otherwise I'll update it with a given value.

Here's my code:

    public static void SetProperty(this object @this, string name, object value)
    {
        var p = @this.GetType().GetProperty(name);
        if (p != null)
        {
            var v = p.GetValue(@this, null);
            if(v == null) p.SetValue(@this, value, null);
        }
    }

The problem is that v is never NULL, which is baffling me. Any help appreciated.





Casting a Delegate into an Action

I'm trying to improve my reflection code by creating Delegates for the Getter and Setter methods.

My code looks like this:

MyObject obj = new MyObject();
var prop = obj.GetType().GetProperty("Prop");
var getType = typeof(Func<>).MakeGenericType(prop.PropertyType);
var setType = typeof(Action<>).MakeGenericType(prop.PropertyType);

var getMethod = prop.GetGetMethod().CreateDelegate(getType, obj);
var setMethod = prop.GetSetMethod().CreateDelegate(setType, obj);

// I'd like to change this section and not to use a dynamic!!
dynamic castedGet = Convert.ChangeType(getMethod, getType);
dynamic castedSet = Convert.ChangeType(setMethod, setType);

CreateDelegate returns a Delegate and using DynamicInvoke isn't performance wise.

I casted (hardcoded) the Delegate into Action<T> \ Func<T> and saw a huge increase in my performance.

I then tried to cast the Delegate into Action<T> \ Func<T> in runtime (using Convert.ChangeType and dynamic) and my performance got hurt - probably due to the fact that I'm using a dynamic type.

I'm pretty sure that I can do this without dynamic.

I guess the solution has something to do with expression trees, but I'm not really sure how to code something like this. If someone has a good solution that doesn't use expression trees than it will be interesting to hear about it as well.





How to execute TestNG test methods in sequence order using JAVA reflection

I have a @Test method(ParentClass) and named as mainTest, and had situation to call n number of @Test methods which is in another class(ClassA(test1,test2), ClassB(test3,test4)) files, and declared inside of the mainTest. When I execute the mainTest method It has to execute the @Test methods which is called inside of mainTest in sequence order using reflection. Can somebody give me any inputs?





How to set priority for test methods execution using TestNG + JAVA Reflection

I have trying to execute my test script with the help of reflections which has annotated as @Test as following way:

Class<?> className = Class.forName(format);  //Load the class name at runtime

                Constructor<?> customConstructor = className.getConstructor(WebDriver.class);   //Create customized constructor and initalize driver from testbase


Method[] method = className.getMethods();  //Call the list of methods in current class file

                for (Method me : method) {
                    if (me.getName().startsWith("test")) {   //Check wheather the class prefix as test

                        Method getMethods = Class.forName(format).getDeclaredMethod(me.getName());   //Loading all the methods at runtime.
                        if(getMethods.isAnnotationPresent(Test.class))
                        {
//The method which is annotated @Test will execute here, using invoke() method of reflection.
}
}

But, the problem is not able to run the @Test methods as per priority value. Its executing randomly. Can anybody tell me how could I run the @test methods based on priority value.





How can I generate a Java factory at compile time?

I have an interface that has been implemented maybe 50 times and my app will keep on evolving with new implementations. These implementations should be loaded depending on their name (which is a constant available in each implementation).

I want to avoid using reflection at runtime (because the reflections lib pulls 3Mb of dependencies and I need to keep my jar as small as possible) and I would also like to avoid having to add an entry to my factory each time an Implementation is added.

So I was wondering: how can I do this automatically at compile time ? I would basically only need to build a map of Implmentation.NAME => ImplmentationConstructor

Thanks