jeudi 31 mars 2016

Java Jackson serializer grab variable name

I have a class structure like so:

public class Foo {
    private Foo2 title;
    private Foo2 message;
}

public class Foo2 {
    private String value;
    private String variable;
}

When I serialize these classes into json I want to output the following json:

{
    "type": "title",
    "value": "...",
    "variable": "..."
},
{
    "type": "message",
    "value": "...",
    "variable": "..."
}

I made a custom serializer class like so:

public class FooSerializer extends JsonSerializer<Foo> {
    @Override
    public void serialize(Foo value,
                          JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("type", /* get variable name */);
        gen.writeStringField("value", value.getValue());
        gen.writeStringField("variable", value.getVariable());
        gen.writeEndObject();
    }
}

But I'm not sure how to get the variable name. Am I going about this the right way? If so, how do I get the variable name?





Create generic type template from string

I have the following piece of generic code.

var base_generic_type = typeof(ConsumerService<,>);

I'd really like to be able to use a string to create this type for example

var base_generic_type = Type.GetType(serviceTypeName, true);

But I can't quite figure out the syntax for creating the generic type template from a string.

I would be most grateful if someone could provide some pointers, all the generic type questions on StackOverflow I can find all start out knowing the basic template type.





Is it safe to call kclass.memberProperties on an unknown (Any) object?

I assumed that it's OK to just access members field of a KClass object. But I have found a case when it's not. Both tests throw exceptions.

@Test fun mapProperties() {
    val map = mapOf("a" to "b")
    val cls = map.javaClass.kotlin
    cls.members
}

Throws: kotlin.reflect.KotlinReflectionInternalError: Incorrect resolution sequence for Java field public open val values: kotlin.collections.MutableCollection<(V..V?)> defined in java.util.Collections.SingletonMap[JavaPropertyDescriptor@10163d6]

@Test fun mapProperties2() {
    val map = mapOf("a" to "b")
    val cls = clsByReified(map)
    cls.members
}

inline fun <reified T: Any> clsByReified(instance: T): KClass<T> {
    return T::class
}

Throws: kotlin.reflect.KotlinReflectionInternalError: No metadata found for public abstract val entries: [Not-computed] defined in kotlin.collections.Map[DeserializedPropertyDescriptor@5c1a8622]

Not sure if I stumbled upon a bug or just missing something.





How do I find any attributes in calling code?

I have a test setup where I decorate tests with attributes telling if a test can run under some circumstances. Deep down in my code I want to check if the test method has a certain attribute. Can this be accomplished?

My tests look like this:

[TestClass, ParallelSeleniumTest, ExcludeFromCodeCoverage]
public class ExportIncident : ViewTest
{
    [TestMethod, TestCategory("ExcludeFromBuildServer"), SupportedBrowsers(Browser.FireFox)]
    public void Export()
    {
        ...
    }
}

And deep down where I want to assert the SupportedBrowserAttributevalue my code looks like this:

internal static RemoteWebDriver CreateDriver()
{
    RemoteWebDriver driver;

    // ReSharper disable HeuristicUnreachableCode
    switch (TestRunSettings.BrowserToUse)
    {
        case Browser.Firefox:
            driver = CreateFirefoxDriver();
            break;
        case Browser.Chrome:
            driver = CreateChromeDriver();
            break;
        case Browser.InternetExplorer:
            driver = CreateInternetExplorerDriver();
            break;
        default:
            throw new ArgumentOutOfRangeException();
    }

    InitDriver(driver);

    return driver;
}

BrowserToUse is a constant in a file.





JUnit Parameterized tests not running in isolation with Mockito, Spring, Reflection and AspectJ

I have the below test class, which has been stripped to the bare minimum needed to reproduce the issue:

@RunWith(Parameterized.class)
@ContextConfiguration(locations = { "classpath:restful-service-test-context.xml" })
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class ResftulServiceTest {

    @Autowired
    @Qualifier("failedAspectTestMessage")
    private String failedAspectTestMessage;

    @Autowired
    private ProviderService ProviderService;

    private String methodName;
    private Set valuesToReturnByMock;
    private TestContextManager testContextManager;

    public ResftulServiceTest(String methodName, String[] valuesToReturnByMockArray) {
        this.methodName = methodName;
        this.valuesToReturnByMock = new HashSet<>(Arrays.asList(valuesToReturnByMockArray));
    }

    @Parameterized.Parameters
    public static Collection values() {
        return Arrays.asList(new Object[][] { { "getCountries", new String[] { "GB", "US" } }, });
    }

    @Before
    public void setUpSpringContext() throws Exception {
        testContextManager = new TestContextManager(getClass());
        testContextManager.prepareTestInstance(this);
    }

    @Test
    public void testGetValues_Fail_MyException() throws Exception {
        Method methodInProviderService = ProviderService.class.getDeclaredMethod(methodName);

        Mockito.when(methodInProviderService.invoke(ProviderService))
                .thenThrow(new MyException(failedAspectTestMessage, StatusCodeType.ERROR));
    }

    @Test
    public void testGetValues_Fail_Exception() throws Exception {
        Method methodInProviderService = ProviderService.class.getDeclaredMethod(methodName);

        Mockito.when(methodInProviderService.invoke(ProviderService))
                .thenThrow(new AspectException(failedAspectTestMessage));
    }
}

If I run each of the tests separately, they work fine. However, if I run all of them, testGetValues_Fail_Exception fails on the Mockito line with error:

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com<obfuscated>.ResftulServiceTest.testGetValues_Fail_Exception(ResftulServiceTest.java:111)
    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)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    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)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: com.<obfuscated>.MyException: FAILED_ASPECT_TEST_MESSAGE
    ... 40 more

If I replace the .thenThrow in testGetValues_Fail_MyException with .thenReturn, it all works fine, so at some point the isolation is being broken. How can I fix this problem?





Why int32(0) is not reflect.DeepEqual to type Zero in Golang?

I found this sort of validation in go-swagger package.

// Required validates an interface for requiredness
func Required(path, in string, data interface{}) *errors.Validation {
    val := reflect.ValueOf(data)
    if reflect.DeepEqual(reflect.Zero(val.Type()), val) {
        return errors.Required(path, in)
    }
    return nil
}

I tried to use it and it forced me for some thoughts.

Why the following is not a true statement?

exper := int32(0)
reflect.DeepEqual(
   reflect.Zero(reflect.ValueOf(exper).Type()), 
   reflect.ValueOf(exper)
)





What's the difference between Type.IsSubclassOf and TypeInfo.GetSubclassOf?

I just noticed there are two methods to check if a class is derived from another class:

Is there any reason this newer method was created? From what I see they both do the same.





Invoking external types that call files via relative path

I'm working on a project that provides third party developers with an API containing template classes they can inherit from. This developer must inform the main process that they've created a type that inherits from one of those templates. To do this, the developer calls a function:

internal Dictionary<string, Type> Templates = new Dictionary<string, Type>();

public void RegisterTemplate(string ID, Type template)
{
    ...
    Templates.Add(ID, template);
    ...
}

Note: RegisterTemplate is a member of the program, not of an external library.

Functions in the type a developer provides in to this function call relative paths such as "Audio/somefile.wav" or "Models/somefile.vox". The third party developer compiles their inheriting classes into a DLL and places it in a folder separate from the program in order to be imported later by the program.

If the program calls the functions described in bold above, will the path associated be relative to the program that invokes the Type, or relative to the DLL that the invoked Type originates from?


To Clarify: rather than the relative paths of the executing assembly or DLL, I'm talking in regards to the paths called within the DLL, like so:

File.Open("Audio/somefile.wav");

If this code is called from a function within the DLL, and the type that contains this code is invoked by code in my executable, will this path be relative to the executable that invoked the Type, or the DLL that contains the invoked Type?





mercredi 30 mars 2016

Extract function name from a function

How can I create a function called getFuncName that takes a function of type (unit -> 'a) and returns its name.

I was talking to one of the C# devs and they said you could use the .Method property on a Func type as shown in an example here. I tried to convert this to F# for example convert (unit -> 'a) to a type Func<_> then call the property on it but it always returns the string "Invoke".

let getFuncName f =
    let fFunc = System.Func<_>(fun _ -> f())
    fFunc.Method.Name

let customFunc() = 1.0

// Returns "Invoke" but I want it to return "customFunc"
getFuncName customFunc

Is this possible?





C# - check if list contains an object where a property equals value?

Is there a shorthand way to do it that does not involve loops?

public enum Item { Wood, Stone, Handle, Flint, StoneTool, Pallet, Bench  }

public struct ItemCount
{
    public Item Item;
    public int Count;
}

private List<ItemCount> _contents;

so something like:

if(_contents.Contains(ItemCount i where i.Item == Item.Wood))
{
    //do stuff
}





How to search a class within a namespace by the value of an attribute and return an object?

I need to make a factory of various objects. To be as abstract as possible. Able to create various objects, from a past condition by parameter, but without knewest concrete classes.

I want to do this by passing a value of an enum into a factory and it must be able, through reflection, to look for all classes within a namespace, which use the attribute whose value is the same as the last parameter.

I'm leaving the following code snippets to be used as reference.

An example of concrete class:

[Batatinha(SaborCode.Churrasco)]
internal class BatatinhaChurrasco : AbstractBatatinha
{
    public override string Sabor
    {
        get { return "Churrasco"; }
    }
}

An example of this factory:

internal class BatatinhaFactory
{
    internal AbstractBatatinha GetBatatinha(SaborCode sabor)
    {
        // Some logic ... possibly using reflection.
    }
}

An example of the desired call:

AbstractBatatinha batatinha = new BatatinhaFactory().GetBatatinha(SaborCode.Churrasco);
Console.WriteLine(batatinha.Sabor);
// ==> "Churrasco"





How do I get Assembly name from full assembly string?

I have a string like this:

"MyProduct.Framework.Business.ShopBusiness"

But the assembly name it self is only:

"MyProduct.Framework.Business"

I need to create a string like this:

"MyProduct.Framework.Business.ShopBusiness, MyProduct.Framework.Business"

Because I'm trying to solve this problem: http://ift.tt/1ZLLgCB

So basically I have this:

Type executingClass = Type.GetType(TestContext.FullyQualifiedTestClassName);

And I need something like this:

Type executingClass = Type.GetType(TestContext.FullyQualifiedTestClassName + ", " + Assembly.FromString(TestContext.FullyQualifiedTestClassName));

Is there any built-in method as I invented "Assembly.FromString()" above?

I know it's not difficult to create one, but I would like to know if this method already exists.





How can I invoke a method without knowing the count of parameters using java.lang.reflect?

I read a tutorial about java.öang.reflect and found a way to get a method from a class and invoke it with given parameters like that:

Method method = /*some initialization*/;
Object returnValue = method.invoke(null, "parameter-value1");

This calls the static method "method" which takes "parameter-value1" as its only parameter.

Now that's pretty neat, but it is not sufficiently dynamic. I want to invoke a method I only have the method-object of and insert an unspecified number of parameters. Let's say I have Method method and Object[] parameters (to be used as parameters for the invocation of method).

Is it possible to write a short and simple method to call any method with given arguments by using reflect? If so: How to archieve this?





Get all class implement specific interface Without loading the assemblies first (dlls)

I would like get a list of all classes implement a specific interface without loading the dll\s first.

Currently I use this code:

Assembly assembly = Assembly.LoadFile(dllPath);
var instances = from t in assembly.GetTypes()
                where t.GetInterfaces().Contains(interfaceType) &&
                t.GetConstructor(Type.EmptyTypes) != null
                select t.Name;
return instances.ToList();

The problem with this code is that it loads all the dependent dlls first, before getting the class names.





How do programs know the types at runtimes of primitives statically typed languages

Both Go and Scala provide ways of checking types at runtime:

Scala:

class A
class B extends A

val a: A = new A // static type: A dynamic type: A
val ab: A = new B // static type: A dynamic type: B
val b: B = new B // static type: B dynamic type: B

def thing(x: Any): String = x match {
    case t: Int => "Int"
    case t: A => "A"
    case t: B => "B"
    case t: String => "String"
    case _ => "unknown type"
}

Go:

package main

import (
    "fmt"
    "reflect"
)

struct A {
    field1 int
    field2 string
}

func printTypeOf(t interface{}) {
    fmt.Println(reflect.TypeOf(t))
}

func main() {
    i := 234234 // int
    s := "hello world" // string
    p := &A{3234234, "stuff"} // *A

    fmt.Print("The type of i is: ")
    printTypeOf(i)
    fmt.Print("The type of s is: ")
    printTypeOf(s)
    fmt.Print("The type of p is: ") // pass a pointer
    printTypeOf(p)
    fmt.Print("The type of the reference of p is: ") // pass a value
    printTypeOf(*p)
}

How exactly does this work internally? I presume for structs and classes, the type of the object is stored in a hidden field (so the structure in golang is really struct { field1 int field2 string type type }. But how on earth can function be given 11010110 and know whether it's a pointer to memory address at 214, the integer 214 or the character Ö? Are all values secretly passed with a byte which represents its type?





Identify non builtin-types using reflect

I need to differentiate such types as

type A []byte

from a []byte. Using reflect, reflect.TypeOf(A{}).Kind tells me that it is a Slice of byte. How can I differentiate []byte{} from A{}, without having a bounded list of types to check for?





Interpreted language in Java and calls to Java methods

I have implemented simple interpreted language with dynamic typing in Java. Unfortunately I ran into the following problem. When testing the following code:

def main() {
    def ks = Map[[1, 2]].keySet();
    return ks.size();
}

I stumbled upon the following exception:

java.lang.IllegalAccessException: class is not public: java.util.HashMap$KeySet.size()int/invokeSpecial

Of course This is true and caused by the fact that HashMap$KeySet class has "package" visibility. This means that when I call it's "size()" method, I call method from class that is not visible to my code. Java avoids this problem easily - method keySet() returns value of type Set, so method size() used is declared in public and abstract class "Set".

My question is: does anyone has an idea, how this should be handled in generic way? By "general" case I mean not only this simple case, where I can walk through whole inheritance chain and find "first declaration" of this method, but also pathological cases like the following:

interface I1 {
    public void foo();
}
interface I2 {
    public void foo();
}
interface I3 {
    public void foo();
}
class C implements I1, I2, I3 {
    public void foo() { .... }
}

My current impression is that I could ignore those pathological cases and select any matching method on the grounds that if such object exists, then it's creation was successful, so it's compilation was successful, so all these methods have identical signatures and since in Java there is no way to specify different implementations of these methods depending on how object is viewed (as I1, I2 or I3), then result will be always the same.

Any help will be appreciated.





MVC Expose class and assembly name in View, what are the risks?

I have view model class: DummyClass.cs in project: ViewDataModels. Running MVC Razor app is named MyWebApp. In this web app I have View /Home/Index.cshtml and form with hidden field where is line of code that exposes DummyClass AssemblyQulifiedName

'@typeof(DummyClass).AssemblyQualifiedName'

results in

ViewDataModels.DummyClass, ViewDataModels, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

so in post I can through reflexion get class type that represens model. What are the risks here? Are there any work arounds? For ex.: two way hash of the string?





mardi 29 mars 2016

Java Singleton Access by Reflection

I'm working on a class where it is supposed to access an Singleton's class methods using reflection. Are there any best practices in here or pitfalls? Thanks in advance





It is possible to set property value via reflection in nsubstitute proxy object?

Im trying to mock interface and set properties via reflection. But I get null reference exception. Is any way to do this ? I also create instance of this proxy by FormatterServices.GetSafeUninitializedObject(). enter image description here





Java: Dynamic List Type to cast Json array

Well, I have this: A number of webservices, each webservice returns an array of one entity. Good!

In my Android app, I call the webservices and get the Json String with the array of elements.

To make it some dynamically I made an array with the cast classes names, example:

<item>com.company.package.Person</item>
<item>com.company.package.Animal</item>
<item>com.company.package.Thing</item>
// etc

The idea was:

  1. Load the array with the name of the class to cast the JSON

    String[] entities = getResources().getStringArray(R.array.classNames);
    
    
  2. Get a Class type with Class.forName(...)

    Class<?> object = Class.forName(entities[y]); 
    
    
  3. Always the webservices returns an array, then I want to convert the Json to Java List like this

    //see the **object**, this was my idea but doesn't work
    Type type = new TypeToken<List<**object**>() {}.getType();
    List<**object**> array = gson.fromJson(jsonArrayString, type);
    
    

Any way to do this?





lundi 28 mars 2016

Handling generic properties via reflection

If I have the following wrapper class:

public class Wrapper<T>
{
    public T Data { get; set; }
    public string[] Metadata { get;set;
}

and another class then exposes that value without generics:

public class SomeOtherClass
{
    public object WrappedData { get;set };
}

, how can I get at the original unwrapped data?

I can test for it, using something like:

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Wrapper<>))
{
    dynamic originalValue = someOtherClass.WrappedData;
}

but I can't then call the .Data property on originalValue, getting a RuntimeBinderException.





Selecting a class method using Lambda Expression

Currently in my code I have a method like this:

.AddMethod(nameof(IRoleService.GetRoles))

What Im trying to do is selecting the interface method using lambda expression and then get the name of method inside AddMethod. So the result would be :

.AddMethod<IRoleService>(x=> x.GetRoles)

I have tried this:

AddMethod<T>(Expression<Func<T, Action>> expression);

But the problem is some of the interface methods have input parameters which I'm trying to ignore, as I just need the method name. Would be thankful if you help me with this.

Alex





How should I select which concrete implementation should be instantiated based on the user choice?

I have an interface Fruit with two implementations Apple and Banana. I want to create a Fruit instance. The choice whether the concrete implementation should be an Apple or a Banana should be made by the user. I did not yet design the user interface, so there is no restriction how this choice is made by the user.

I know there are the following options:

  1. usage of the abstract factory pattern
  2. usage of reflection to create an instance from a given class name
  3. usage of reflection to create an instance from a given class object

What are the pros and cons of these options?


Please note that while there are several similar questions that discuss the one or the other approach, I did not find a single comparison.

Here is a list of related questions:





How to get parameter type in reflected class method?

I'm trying to get type $bar variable.

<?php
class Foo
{
    public function test(stdClass $bar)
    {

    }
}

$reflect = new ReflectionClass('Foo');
foreach ($reflect->getMethods() as $method) {
    foreach ($method->getParameters() as $num => $parameter) {
        var_dump($parameter->getType());
    }
}

I expect stdClass but I get

Call to undefined method ReflectionParameter::getType()

What can be wrong? Or there is some another way?..

$ php -v
PHP 5.4.41 (cli) (built: May 14 2015 02:34:29)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies





Open Saved ReflectionIBM.Session using vba

I have a rather simple task that I am trying to achieve but am having trouble. I am trying to open a .rdx file from visual basic. It is run using Reflection. I have tried some methods such as

 Dim Shex As Object
   Set Shex = CreateObject("ReflectionIBM.Session")
   tgtfile = "I:\filepath\Attachmate\123Screen.rd3x"
   Shex.Open (tgtfile)

but can't seem to get it to work and i'm unable to find solutions from other posts.

Please let me know if I can provide anymore information.

Kindest Regards,

Alex





getDeclaredConstructors() return java.lang.NullPointerException

I'm using a java web framework (Vraptor) and I'm having the following problem: The frameworks uses Reflection to instantiate the Controllers parameters, and for some reason one of the Parameters is returing <java.lang.NullPointerException>.

My question is: the framework works normally for a while, and for some reason the "cachedConstructor" of the type I want to instantiate is filled with <java.lang.NullPointerException> instead of what is expected. What could possible make that change?

I'm not asking if the framework is doing this, I just want to know what could do this in Java

getClassType().getDeclaredConstructors() is return java.lang.NullPointerException (returning, not throwing)





How can I rewrite a reflection code with FastMemeber library?

I want to get context form DbSet with below code, because Reflection is heavy I want to rewrite blow code with another code with better performance

Can anyone help me for a solution with better performance or rewriting code with FastMember library ?

    public static DbContext GetContext<TEntity>(this DbSet<TEntity> dbSet)
    where TEntity : class
    {
        object internalSet =
            dbSet
            .GetType()
            .GetField("_internalSet", BindingFlags.NonPublic | BindingFlags.Instance)
            .GetValue(dbSet);
        object internalContext = internalSet
            .GetType()
            .BaseType
            .GetField("_internalContext", BindingFlags.NonPublic | BindingFlags.Instance)
            .GetValue(internalSet);
        return (DbContext)internalContext
            .GetType()
            .GetProperty("Owner", BindingFlags.Instance | BindingFlags.Public)
            .GetValue(internalContext, null);
    }

Thanks





dimanche 27 mars 2016

Kotlin reified generic parameter actual type arguments

Using reified type parameters, one can write an inline function which works with the type parameter through reflection at runtime:

inline fun <reified T: Any> f() {
    val clazz = T::class
    // ...
}

But when f is called with a parameter which is itself a generic class, there seems to be no way to obtain its actual type arguments through T::class:

f<List<Integer>>() // T::class is just kotlin.collections.List

Is there a way to get actual type arguments of a reified generic through reflection?





Java- Declare an object of a type chosen by the user

I don't know if this is possible, but what I'd like to know is the following:

Let's say I have an array which contains 2 different class type:

Fruit[] fruit;
fruit[0]= new Banana();
fruit[1]= new Apple();

What I want to do is this:

Fruit unknown= new fruit[0].getClass();

I want to declare an object of a type which is chosen by the user. Can I do it?





how to convert reflection from wp8.1 silverlight to wp8.1

I am using vs2015, I developed an app in wp7.1 Silverlight. i upgraded it to wp8.1 Silverlight. When i try to publish it to the store it does not pass the certification. i made some tests and i decided to convert it to wp8.1 to pass the certification.

During the process of conversion from wp8.1 Silverlight to wp8.1, I have some difficulties in reflection because it is not the same as in win8.1 Silverlight.

I have this method (in wp8.1 Silverlight compile without errors). could some one help me to write it in wp8.1.

  public ByConventionMapperStrategy(Type entityType, bool publicOnly)
        : base(entityType, publicOnly)
    {
        //map members that are properties
        ColumnPredicate = m => m.MemberType == MemberTypes.Property;

        //map members that are properties and icollection types.
        RelationshipPredicate = m =>
            {
                return m.MemberType == MemberTypes.Property && typeof(ICollection).IsAssignableFrom((m as PropertyInfo).PropertyType);
            };
    }

    public Func<MemberInfo, bool> ColumnPredicate;
    public Func<MemberInfo, bool> RelationshipPredicate;

excuse me for my English. thank you for help.





samedi 26 mars 2016

Selected Item Is Null

I am making a plugin system for my application and I am using reflection to add controls to a TabPage. For the controls that have a SelectedItem attribute it is always null even if an item is selected.

Here is the code I am using to load the plugins:

                Assembly assembly = Assembly.LoadFrom(file);
                Type[] types = assembly.GetTypes();
                Boolean ContainsIPlugin = false;
                String pluginname = file.Substring(file.LastIndexOf("\\") + 1);
                pluginname = pluginname.Substring(0, pluginname.LastIndexOf("."));
                foreach (Type type in types)
                {
                    // if we found our interface, verify attributes
                    if (type.GetInterface("IPlugin") != null)
                    {
                        ContainsIPlugin = true;

                        MethodInfo methodInfo = type.GetMethod("LoadPlugin");

                        // create the plugin using reflection
                        IPlugin pluginobj = Activator.CreateInstance(type) as IPlugin;

                        var result = methodInfo.Invoke(pluginobj, null);

                        // get custom attributes from plugin
                        UTCPlugin newplugin = new UTCPlugin(pluginobj);
                        newplugin.name = pluginobj.PluginDisplayName;
                        newplugin.version = pluginobj.PluginVersion;
                        newplugin.description = pluginobj.PluginDescription;
                        newplugin.author = pluginobj.PluginAuthor;

                        loadedPlugins.Add(newplugin);
                    }
                }

If I could get some help fixing this that would be a big help. Thanks!





Convert string value to function call

I want to specify a function based on a string. I'm getting strings out of a map, in the example below they are the values in function while interating ove the map. Now for example, when the string value function == "networkInfo", I would like to "treat" that value as a real functions' name. It's hard to explain, but I think you guys will know what I mean.

My goal is to remove the switch statement and directly call c.AddFunc(spec, func() { networkInfo() }) where networkInfo is the function name, extracted from string function. I know this is possible, but I don't know how :(. Help is appreciated!

// ScheduleCronjobs starts the scheduler
func ScheduleCronjobs() {

tasks := props.P.GetStringMapString("tasks")
log.Infof("number of tasks: %d", len(tasks))

if len(tasks) != 0 {
    c := cron.New()

    // for each task, initialize
    for function, spec := range tasks {
        switch function {
        case "networkInfo":
            c.AddFunc(spec, func() { networkInfo() })
        case "bla":
            c.AddFunc(spec, func() { bla() })
        default:
            log.Errorf("unknown task: %q", function)
        }
    }
    c.Start()
}

// after initialization, send out confirmation message
slack.SendMessage("tasks initialized", props.P.GetString("channel"))
}





Working with custom annotations

So today I tried to create my custom annotation to represent a set of attributes but I need a void to execute some kind of functionality with the set of attributes provided.

I'm looking for something similar to

Public @interface CommandSignature {

String[] alias();

Rights[] rights();

String syntax();

void execute();

}

and a sub-class would look like

@CommandSignature(
    alias = { "hello" }, 
    rights = { Rights.USER}, 
    syntax = "Use this command as ::hello"
)
public final class Test {

    @Override
    public void execute() {
        System.out.println("this is not possible since custom annotations cannot hold void methods");
    }
}

As u can see that's not possible since a custom annotation class cannot hold void methods.

So the solution would be defining a new interface which holds an #execute method.

public interface Command {

void execute();

}

But how would I retrieve the execute and the command signature for each sub-class in a specific directory? I'm sure reflection is the way to go but I can't wrap my mind around it.

tl;dr how can I call execute and retrieve the annotations of that sub-class.

Keep in mind, I might end up with 20-30 classes so defining each value in a list is not prefered unless done with reflection on startup.





Is reflection is slow/unusable "out of the box"?

Some background. I need to parse an xml response from some api, looking like kinda like this:

    <Customer> 
       ...
       <Telephone1></Telephone1>
       <Telephone2></Telephone2> 
       <Telephone3></Telephone3>
       ...
    </Customer>

I am using scalaxb to unmarshall this into a case class, but I don't want the downstream code exposed to this sort of badness, so I want to replace this "row" object with something like

 case class Customer(
   name: String,
   ...
   telephones: Seq[String]
   ...
 )

There are many different objects like this, and I don't want to be writing all these repetitions of Seq(telephone1, telephone2, telephone3 ...) for different fields by hand, but would prefer to make a generic converter, that can handle all types using reflection.

Now, this is (going to be) production code, and I am worried about performance. I have not used reflection in production for many years, not since java 1.4, I think, and back than it was unusably slow. People had to use special libraries, like CGLib, in order to get close to decent performance and scalability.

Now, my question is whether this is still the case. If I end up using reflection in scala, will the standard implementation that scala (or java) has work, or am I going to have to use tricks like CGLib, building my own method caches etc.?





public static runtime incremental change - android

I have a simple class named A which has two private fields.

public class A {

    private String a;
    private String b;
} // A

When I get all declared fields from class instance, I get one extra field named $change. Where is it coming from ? I am totally not getting this.

Field[] fields = cls.getDeclaredFields();
        for (int i = 0, len = fields.length; i < len; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            Log.d("TAG", field.getName());
            if (field.isAnnotationPresent(Primary.class)) {
                query += getFromalName(field.getName()).toUpperCase() + " " + getSchemaType(field.getType().getSimpleName()) + " PRIMARY KEY, ";
                continue;
            }
            if (field.isAnnotationPresent(NotNull.class)) {
                query += getFromalName(field.getName()) + " " + getSchemaType(field.getType().getSimpleName()) + " NOT NULL, ";
                continue;
            }
            query += getFromalName(field.getName()) + " " + getSchemaType(field.getType().getSimpleName()) + ", ";
        } // end for

        query = query.substring(0, query.lastIndexOf(","));
        query += " )";

Here is the snapshot

Snapshot 2





HOW TO ADD ALL CLASS OBJECTS IN ARRAYLIST

I Want to add all classes object to Arraylist. As per the convectional way I can add it but I need a generic way to add it; even if i add one more class in my package its object should be added to the Arraylist before running main script.

I did attached the screenshot of classes and Arraylist addition.

Can you please provide me a way, how can I add the object of all classes on the flow to Arraylist?

enter image description here

enter image description here





Will reflection keeps the semantics of volatile in java

For example, when I modified a volatile field in one thread, the JMM would guarantee that then the new value will be visible to the other thread.

My question is, is this still true when I use reflection to modify the field?

The following code is just an example to show how reflection works.

import java.lang.reflect.Field;

public class ReflectionDemo {
    private volatile boolean flag = false;

    /**
     * using reflection to modify a filed
     *
     * @param target target object
     * @param value  new value
     */
    public static void modify(ReflectionDemo target, boolean value) {
        try {
            Field field = ReflectionDemo.class.getDeclaredField("flag");
            field.setAccessible(true);
            field.setBoolean(target, value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ReflectionDemo demo = new ReflectionDemo();
        System.out.println(demo.flag);

        ReflectionDemo.modify(demo, true);
        System.out.println(demo.flag);
    }

}





vendredi 25 mars 2016

How do I get the Type of a generic parameter for a given method

Ok, here's the problem. I have a problem when comparing the return type of two different methods.

The first method is hard coded to a specific generic type, so when you get information on the method return type, it includes the type. Here's what I mean.

public Task<Message> GetMessage(long id)
{
    ...
    return await getEntityFromDbById<Message>(id); //generic type is hard coded to type Message
}

If you get the method info this.GetType().GetTypeInfo().GetDeclaredMethod("GetMessage").ReturnType.ToString(), and look at it's return type, this is what you get

System.Threading.Tasks.Task`1[Core.Models.Message]

Now, my second method is generic and looks like this.

public Task<T> GetEntityById<T>(long id) where T : class, IEntity
{
    ...
    return await getEntityFromDbById<T>(id); // generic type is passed in
}

Now if you get the ReturnType information for this method you get

System.Threading.Tasks.Task`1[T]

What I'm trying to do at runtime, is get the type information of T and compare it to the other method using only MethodInfo types. How can this be done?

public bool compareMethods(MethodInfo method1, MethodInfo method2)
{
    ...
    //Won't work because one method has a generic return type. 
    //How do you detect and compare?    
    return method1.ReturnType == method2.ReturnType; 
}





scala macro reify local variable

I'm trying to write a simple macro to pull public fields from a class, along with their 'schema' (for Spark SQL). Now, a schema is simply a string name, and a spark sql DataType (StringType, BooleanType for example). I'm pattern matching to convert from a Scala type to a spark sql type. BUT, I can't seem to get the local variable (dt, a spark sql DataType) into my tree.

Weird thing is, if I replace dt with the literal StringType, it works perfectly. If it can do that, I'm not sure why it can't take it from a variable. Even doing val dt = StringType doesn't work.

I feel like there is some way of doing something like c.Expr[DataType](Select(<local variable>).splice() but I can't figure it out.

import scala.language.experimental.macros
import scala.reflect.macros.whitebox
import org.apache.spark.sql.types.{DataType, StringType, BooleanType}

object DataExtractor {
  case class SomeField(name: StructField, value: Any)
  type SomeData = Seq[SomeField]

  implicit class DataExtraction[M <: DataExtractor](val model: M) extends AnyVal {
    def allData: SomeData = macro Macros.impl[M]
  }

  private object Macros {
    def impl[T: c.WeakTypeTag](c: whitebox.Context): c.Expr[SomeData] = {
      import c.universe._

      val applier = Select(reify(Seq).tree, TermName("apply"))
      val model = Select(c.prefix.tree, TermName("model"))

      val terms = weakTypeOf[T].members.collect {
        case m: MethodSymbol if m.isGetter && m.isPublic => m
      }.map( t => {
        val name = t.name.decodedName.toString
        val value = c.Expr(Select(model, t.name))
        val sig: Type = t.typeSignature.resultType

        val dt: DataType = sig match {
          case a if sig =:= typeOf[String] => StringType
          case e if sig =:= typeOf[Boolean] => BooleanType
          case _ => throw new Exception(s"Failed to match a ${sig.toString}")
        }

        reify(ClaimField(
          StructField(c.Expr[String](Literal(Constant(name))).splice, dt),
          value.splice
        )).tree
      })
      c.Expr[SomeData](Apply(applier, terms.toList))
    }
  }
}





C# check if generic type has attribute by string and assign to it

Let's say, I have a class.

class A {
  string X {get; set;}
  string Y {get; set;}
}

and in some method I want to ask, if a generic class (in my case A) has a by string specified argument, and if so, assign to it a value;

class CreateGenerics<T> where T:new()
{
  public List<T> create(string attr, string[] attrValues) 
  {
    //I want to check if T has attribute attr (let's say "X")

    List<T> ret = new List<T>();
    foreach(string value in attrValues) {
      T t = new T();
      //set 'attr' attribute of T to value of 'value'
      ret.Add(t);
    }
    return ret;
  }
}





Android enum reflection

I have been trying for the past few hours to get the following functionality working.

public class OMG {

    String name;
    HashMap<SETTINGS, String> settings;

    public enum SETTINGS {
        Setting1("OMG setting 1"), Setting2("OMG setting 2");
        private String key;

        @Override
        public String toString() {
            return "SETTINGS: " + key;
        }

        SETTINGS(String key){
            this.key = key;
        }
    }

    public OMG(String name, HashMap<SETTINGS, String> settings) {
        this.name = name;
        this.settings = settings;
    }
}

and

public class Test {

    public static void main(String[] args) {
        try {
            Class<?> c = Class.forName("path.to.OMG" + "$" + "SETTINGS");

            System.out.println(Arrays.toString(c.getEnumConstants()));
            HashMap<c,String > values = new HashMap<>();

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

I have to create an OMG instance and am been given the path to OMG and the enum NAME. So far I have the code in the Test class. I am able to get all enumValues however I have no idea how to create a HashMap and how to call the constructor with this HashMap to get an instance of the OMG class.

Please help.

Thank yuo





Compare Two Structs Using Standard Method (Byte Comparison/Reflection) Even If Equals Method Exists

I have some simple struct, which overrides the Equals() method:

public struct Pair<T> {
    public Pair(T x, T y) {
        X = x; Y = y;
    }

    public T X { get; }
    public T Y { get; }

    public override bool Equals(object obj) {
        var otherPair = (Pair<T>) obj;
        return X.Equals(otherPair.X);
    }
}

According to MSDN, value types without an Equals() method are compared as follows:

If none of the fields of the current instance and obj are reference types, the Equals method performs a byte-by-byte comparison of the two objects in memory. Otherwise, it uses reflection to compare the corresponding fields of obj and this instance.

I wish to compare Pairs using the quoted approach instead of using Pair's own Equals() method, so that the following test passes:

[Test]
public void PairsEqual()
{
    var p1a = new Pair<int>(10, 1);
    var p1b = new Pair<int>(10, 1);
    var p2 = new Pair<int>(10, 2);

    Assert.That(p1a, Is.Not.EqualTo(p2));
    Assert.That(p1a, Is.EqualTo(p1a));
    Assert.That(p1a, Is.EqualTo(p1b));
}

This should ultimately work like a ReferenceEqual for structs. Is this possible? Ideally, I would like to replace the comparison with the original ValueType.Equals() method.





Get particular public fields via reflection (for all parent classes)

How to get all fields with particular type from some object instance including all its parent-classes?

For example, there are these classes:

trait Target {
    val message: String
    def action: Unit = println("hello", message)
}

class ConcreteTarget(val message: String) extends Target

trait BaseSet {
  val s = ""
  val t1 = new ConcreteTarget("A")
  val t2 = new ConcreteTarget("B")
  val a = 123
}

class ExtendedSet extends BaseSet {
  val t3 = new ConcreteTarget("C")
  val f = "111"
}

I've tried write method for getting all Target fields:

import scala.reflect.runtime.universe._
import scala.reflect.runtime.{universe => ru}

def find(instance: Any): List[Target] = {
    val m = ru.runtimeMirror(instance.getClass.getClassLoader)
    val i = m.reflect(instance)

    i.symbol.typeSignature.decls.flatMap {
      case f: TermSymbol if !f.isMethod => i.reflectField(f).get match {
        case d: Target => Some(d)
        case _ => None
      }
      case _ => None
    }.toList
}

This method works fine for BaseSet:

find(new BaseSet{}) foreach (f => f.action)
//> (hello,A)
//> (hello,B)

But finds only public fields from ExtendedSet and don't find parents fields:

find(new ExtendedSet) foreach (f => f.action)
//> (hello,C)

What is wrong?





Java: list fields used in a method

In Java, how can I get the Fields that are used in a method ?

Basically, this is the same questions as this one in .NET. I dont wan't to list the fields from a Class, but to list the fields that are used in a given method of the class.

Example:

public class A {
 int a;
 int b;

public int bob(){
 return a-b;
}

I want to get the fields like this:

Fields[] fields = FieldReader.(A.class.getMethod("bob"));

So that fields[0]=A.a and fields[1]=A.b

I didn't find any solution using standard Reflection. Do you think bytecode manipulation library such as ASM are a way to go ?





VB.NET determine project's imported namespaces at runtime

In VB.NET (or C#), how can I determine at runtime which namespaces are imported in the Project properties? I'll be using this for dynamic compilation, I'd like the dynamic code to automatically have the same Imports as its parent project.





jeudi 24 mars 2016

How to use hide method in Android?

I'm new in Android.My phone has two SIM slot,And i want to know secomd SIM card's info.So I want to sue the blowe method in TelephonyManager which is hided. enter image description here

Someone tells me to use reflect,and here is my try.

            Class<TelephonyManager> telephonyManagerClass = TelephonyManager.class;
            TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            try {
                Method method = telephonyManagerClass.getMethod("getSimState", new Class[]{int.class});
                method.setAccessible(true);
                Object object = method.invoke(telephonyManager,1);
                int a = (int)object;
                System.out.println(a);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }catch (Exception e){
                e.printStackTrace();
            }

Unfortunatly, here is exception

 java.lang.NoSuchMethodException: getSimState [int]
 at java.lang.Class.getConstructorOrMethod(Class.java:472)
 at java.lang.Class.getMethod(Class.java:857)
 at (MainActivity.java:61)
 at android.view.View.performClick(View.java:4438)
 at android.view.View$PerformClick.run(View.java:18442)
 at android.os.Handler.handleCallback(Handler.java:733)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:136)
 at android.app.ActivityThread.main(ActivityThread.java:5195)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:515)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:603)
 at dalvik.system.NativeStart.main(Native Method)

Could you help me to fix it?





C# how to get dll assembly information?

If we want to get the version number of a dll we could use,

Assembly assembly = Assembly.LoadFrom("System.Xml");
Version ver = assembly.GetName().Version;

How to get the other information (like AssemblyTitle, AssemblyProduct, etc..) ?

using Reflecter.exe





c# - What does this inheritence + reflection code do

I found the following code snippet which puzzled me.

public class Bclass : Aclass
{
    public const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

    public Bclass(IAclass a) : base(string.Empty)
    {
        var destFields = this.GetType().BaseType.GetFields( Flags );

        a.GetType().GetFields( Flags ).Where(x => destFields.Contains(x)).ToList().ForEach(property =>
        {
            destFields.First(x => x == property).SetValue(this, property.GetValue(a));
        });

        var destProperties = this.GetType().BaseType.GetProperties( Flags );

        a.GetType().GetProperties( Flags ).Where(x => destProperties.Contains(x)).ToList().ForEach(property =>
        {
            destProperties.First(x => x == property).SetValue(this, property.GetValue(a, null));
        });
    }
    // some more methods... 
}

I may have some idea what it does... (leaving it to you as a riddle and to check if I am not missing anything)

My main Q is.... why would anyone think of doing that... What benefit(s) can come out of this code.

(btw. we should change the title once we figure out what it does, and its value)





How to invoke a class method using performSelector() on AnyClass in Swift?

In ObjC you could simply invoke a class method using the class method from NSObject.

[Machine performSelector:@selector(calculate:) withObject:num];

But how do you do this in Swift (2.2)?

@objc(Machine)
class Machine: NSObject {
    static func calculate(param: NSNumber) -> String {
        if param.integerValue > 5 {
            return "42"
        }
        return "42" // there is only 1 answer to all the questions :D
    }
}

if let aClass = NSClassFromString("Machine") {
    let sel = #selector(Machine.calculate(_:))
    let num = NSNumber(integer: 1337)
    let answer = aClass.performSelector(sel, withObject: num) // compiler error
    // let answer = aClass.calculate(num)                     // <-- this works
    print(answer)
}

With above code I'm getting the following compiler error:

error: cannot invoke 'performSelector' with an argument list of type '(Selector, withObject: NSNumber)'

What am I missing here?





Want to avoid copy-pasting method names for a Swift 2 delegate dispatcher

I’m trying to implement a dispatcher to notify multiple targets for a delegate pattern protocol.

What’s a better way of doing the following pattern, without copy-pasting for every method name? Reflection, aspect-oriented programming, meta-programming all come to mind:

public class AirBatteryClientDelegateDispatcher: AirBatteryClientDelegate {
    private var targets = [AirBatteryClientDelegate]()

    public func clientDidStartScan(client: AirBatteryClient) {
        for target in targets {
            target.clientDidStartScan?(client)
        }
    }

    . . .
}

For reference, I’m using the following protocol with a dozen more similar methods:

@objc public protocol AirBatteryClientDelegate: class {
    optional func clientDidStartScan(client: AirBatteryClient)
    optional func clientDidStopScan(client: AirBatteryClient)
    optional func clientDidUpdateState(client: AirBatteryClient)
    . . .
}





Performance for Activator.CreateInstance

I am invoking a method using the following lines of code. Loading the assembly dynamically and executing a method in a class dynamically:

var myModule = Activator.CreateInstance(mytype, true);

MethodInfo myMethodInfo = mytype.GetMethod("Run");
object[] mParam = new object[] { param };
myMethodInfo.Invoke(myModule, mParam);

Is it going to hamper performance considerably. If it is low on performance, is there any other way to make it perform the best retaining the dynamic calling of executing the object?

Thanks





ambiguous match when calling method via reflection

When I try to call JsonConvert.DeserialiseObject via reflection I get an AmbiguousMatchException despite me specifying the type of the parameter for the overload I want to call

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

Not sure what other info I can supply so that it finds a unique match

any ideas?





Reference Variable names as strings

I am trying to reference the name of a variable as a string. I have a list of global variables

Public gvHeight As String = Blank
Public gvWeight As String = Blank
Public gvAge As String = Blank

I need to reference the name of the variables for an external API call. I am trying to avoid specific code per variable, instead allow me to add a new variable and everything reference correctly. I already have the rest of the code to deal with the name as a string.

example:

public Height as string
public weight as string
public age as string

[elsewhere in code]
for each var as string in {public variables}
   CallToAPI(var.name) 'needs to send "height" "weight" or "age" but there are a lot so hardcoding is not a good solution

edited for example





How to get the code to recreate a dataframe in R?

I have some dataframe object.

I want to see the code that recreates that dataframe object.

For example, here is my dataframe

str(ror)
# 'data.frame':   2 obs. of  2 variables:
#  $ from: Factor w/ 2 levels "x","x1": 2 1
#  $ to  : Factor w/ 2 levels "x2","y": 1 2

I want to get the following code to be printed by calling some function such as: recreate(ror)

recreate(ror)
# data.frame(from = c('x1', 'x'), to = c('x2', 'y'))

I remember that there was a function to get this code from ror, but I cannot find the exact name of this function or exact term to search in google to find it?





How is .maxstack calculated by reflection emit?

I am generating a method that has a large number of switch statements. I noticed in ildasm the .maxstack value is really high. My understanding is the .maxstack is the maximum stack depth of a given method? I cannot find to much information about online.

In the first two examples the maximum stack size is over 4KB. In the last example the maximum stack size is 509 but it seems like the actual maximum depth is 10. Why is the value so high? This is just a hint for the jit? Is there an implications of having such a high .maxstack? Is everything I read on the internet about it being the maximum depth incorrect?

class Program
{
    static void Main(string[] args)
    {
        Foo();
        Bar();
        FooBar();
    }

    static void Foo()
    {
        // Increasing this value will increase the stack depth by the number of labels.
        int caseStackDepth = 8;

        string name = Path.ChangeExtension("foo", ".dll");
        AssemblyName assemblyName = new AssemblyName("foo");
        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder module = assemblyBuilder.DefineDynamicModule(assemblyName.Name, name);


        TypeBuilder type = module.DefineType("boo", System.Reflection.TypeAttributes.Class | System.Reflection.TypeAttributes.Public);
        MethodBuilder method = type.DefineMethod(
            "bar", 
            System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Static,
            typeof(int),
            new [] { typeof(int) });

        ILGenerator generator = method.GetILGenerator();
        LocalBuilder result = generator.DeclareLocal(typeof(int));

        Label[] labels = new Label[500];
        for (int index = 0; index < labels.Length; index++)
        {
            labels[index] = generator.DefineLabel();
        }

        Label end = generator.DefineLabel();

        generator.Emit(OpCodes.Ldarg_0);
        generator.Emit(OpCodes.Switch, labels);
        generator.Emit(OpCodes.Br, end);

        for (int index = 0; index < labels.Length; index++)
        {
            generator.MarkLabel(labels[index]);
            generator.Emit(OpCodes.Ldc_I4, index);

            // Simulate stack depth.
            for (int depth = 0; depth < caseStackDepth; depth++)
            {
                generator.Emit(OpCodes.Dup);
            }
            for (int depth = 0; depth < caseStackDepth; depth++)
            {
                generator.Emit(OpCodes.Add);
            }

            generator.Emit(OpCodes.Stloc, result);
            generator.Emit(OpCodes.Br, end);
        }

        generator.MarkLabel(end);


        generator.Emit(OpCodes.Ldloc, result);

        generator.Emit(OpCodes.Ret);

        type.CreateType();

        assemblyBuilder.Save("foo.dll");
    }

    static void Bar()
    {
        // Increasing this value will increase the stack depth by the number of labels.
        int caseStackDepth = 8;

        string name = Path.ChangeExtension("bar", ".dll");
        AssemblyName assemblyName = new AssemblyName("bar");
        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder module = assemblyBuilder.DefineDynamicModule(assemblyName.Name, name);


        TypeBuilder type = module.DefineType("boo", System.Reflection.TypeAttributes.Class | System.Reflection.TypeAttributes.Public);
        MethodBuilder method = type.DefineMethod(
            "bar",
            System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Static,
            typeof(int),
            new[] { typeof(int) });

        ILGenerator generator = method.GetILGenerator();
        LocalBuilder result = generator.DeclareLocal(typeof(int));

        Label end = generator.DefineLabel();

        for (int index = 0; index < 500; index++)
        {
            Label equal = generator.DefineLabel();
            Label notEqual = generator.DefineLabel();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldc_I4, index);
            generator.Emit(OpCodes.Beq, equal);
            generator.Emit(OpCodes.Br, notEqual);

            generator.MarkLabel(equal);
            generator.Emit(OpCodes.Ldc_I4, index);

            // Simulate stack depth.
            for (int depth = 0; depth < caseStackDepth; depth++)
            {
                generator.Emit(OpCodes.Dup);
            }
            for (int depth = 0; depth < caseStackDepth; depth++)
            {
                generator.Emit(OpCodes.Add);
            }

            generator.Emit(OpCodes.Stloc, result);
            generator.Emit(OpCodes.Br, end);

            generator.MarkLabel(notEqual);
        }

        generator.MarkLabel(end);


        generator.Emit(OpCodes.Ldloc, result);

        generator.Emit(OpCodes.Ret);

        type.CreateType();

        assemblyBuilder.Save("bar.dll");

    }

    static void FooBar()
    {
        // Increasing this value will increase the stack depth by the number of labels.
        int caseStackDepth = 8;

        string name = Path.ChangeExtension("foobar", ".dll");
        AssemblyName assemblyName = new AssemblyName("foobar");
        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder module = assemblyBuilder.DefineDynamicModule(assemblyName.Name, name);


        TypeBuilder type = module.DefineType("boo", System.Reflection.TypeAttributes.Class | System.Reflection.TypeAttributes.Public);
        MethodBuilder method = type.DefineMethod(
            "bar",
            System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.Static,
            typeof(int),
            new[] { typeof(int) });

        ILGenerator generator = method.GetILGenerator();
        LocalBuilder result = generator.DeclareLocal(typeof(int));

        for (int index = 0; index < 500; index++)
        {
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldc_I4, index);

            // Simulate stack depth.
            for (int depth = 0; depth < caseStackDepth; depth++)
            {
                generator.Emit(OpCodes.Dup);
            }
            for (int depth = 0; depth < caseStackDepth; depth++)
            {
                generator.Emit(OpCodes.Add);
            }

            generator.Emit(OpCodes.Stloc, result);
        }

        generator.Emit(OpCodes.Ldloc, result);

        generator.Emit(OpCodes.Ret);

        type.CreateType();

        assemblyBuilder.Save("foobar.dll");

    }
}





mercredi 23 mars 2016

how to change property of SelectListItem to selected using reflection

I have a list

    IEnumerable<SelectListItem> workingHoursList = new List<SelectListItem>()
            {
                new SelectListItem() {Text="08:00:00", Value="08:00:00"},
                new SelectListItem() {Text="09:00:00", Value="09:00:00"},
                new SelectListItem() {Text="10:00:00", Value="10:00:00"},
                new SelectListItem() {Text="11:00:00", Value="11:00:00"},
                new SelectListItem() {Text="12:00:00", Value="12:00:00"},
                new SelectListItem() {Text="13:00:00", Value="13:00:00"},
                new SelectListItem() {Text="14:00:00", Value="14:00:00"},
                new SelectListItem() {Text="15:00:00", Value="15:00:00"}
            };

and I would like to change the property of the SelectListItem to selected using reflection. How can I do it?





Can Lambda expressions access private methods of classes outside their scope?

I want to gain reflective access to java.lang.String's package private constructor.

Namely, this one:

/*
* Package private constructor which shares value array for speed.
* this constructor is always expected to be called with share==true.
* a separate constructor is needed because we already have a public
* String(char[]) constructor that makes a copy of the given char[].
*/
String(char[] value, boolean share) {
    // assert share : "unshared not supported";
    this.value = value;
}

Creating a MethodHandle for it is simple enough, and so is invoking it. The same is true for using Reflection directly.

But I'm curious whether it's possible to directly call the constructor via functional interfaces.

27602758 touches on a somewhat similar issue, but the solutions provided do not appear to work in this case.

The test case below compiles without issues. Everything works, except for the actual interface invocation.

package test;

import java.lang.invoke.CallSite;
import java.lang.invoke.LambdaMetafactory;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.lang.reflect.Field;

public class Test {

    // Creates a new String that shares the supplied char[]
    private static interface StringCreator {

        public String create(char[] value, boolean shared);
    }

    // Creates a new conventional String
    private static String create(char[] value, boolean shared) {
        return String.valueOf(value);
    }

    public static void main(String[] args) throws Throwable {
        // Reflectively generate a TRUSTED Lookup for the calling class
        Lookup caller = MethodHandles.lookup();
        Field modes = Lookup.class.getDeclaredField("allowedModes");
        modes.setAccessible(true);
        modes.setInt(caller, -1);   // -1 == Lookup.TRUSTED

        // create handle for #create()
        MethodHandle conventional = caller.findStatic(
            Test.class, "create", MethodType.methodType(String.class, char[].class, boolean.class)
        );
        StringCreator normal = getStringCreator(caller, conventional);
        System.out.println(
            normal.create("foo".toCharArray(), true)
        // prints "foo"
        );

        // create handle for shared String constructor
        MethodHandle constructor = caller.findConstructor(
            String.class, MethodType.methodType(void.class, char[].class, boolean.class)
        );
        // test directly if the construcor is correctly accessed
        char[] chars = "foo".toCharArray();
        String s = (String) constructor.invokeExact(chars, true);
        chars[0] = 'b'; // modify array contents
        chars[1] = 'a';
        chars[2] = 'r';
        System.out.println(
            s
        // prints "bar"
        );

        // generate interface for constructor
        StringCreator shared = getStringCreator(caller, constructor);
        System.out.println(
            shared.create("foo".toCharArray(), true)
        // throws error
        );
    }

    // returns a StringCreator instance
    private static StringCreator getStringCreator(Lookup caller, MethodHandle handle) throws Throwable {
        CallSite callSite = LambdaMetafactory.metafactory(
            caller,
            "create",
            MethodType.methodType(StringCreator.class),
            handle.type(),
            handle,
            handle.type()
        );
        return (StringCreator) callSite.getTarget().invokeExact();
    }
}

Specficially the instruction

shared.create("foo".toCharArray(), true)

throws the following error:

Exception in thread "main" java.lang.IllegalAccessError: tried to access method java.lang.String.<init>([CZ)V from class test.Test$$Lambda$2/989110044 at test.Test.main(Test.java:59)

Why is this error still being thrown, despite access ostensibly being granted?

Can anyone come up with an explanation for why the generated interface has no access to a method that all of its components have access to?

Is there a solution or a viable alternative that actually works for this particular use case, without reverting to pure Reflection or MethodHandles?

Because I'm stumped.





Java 8 Reflections error: java.lang.IllegalArgumentException: wrong number of arguments

When i execute the doGet of this servlet, i get an java.lang.IllegalArgumentException: wrong number of arguments. the complete code is this:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    map = new HashMap<>();

    cl = new Configuration().getClass();
    Method[] m = cl.getMethods();

    for (int i = 0; i < m.length; i++) {
        if (!m[i].getName().startsWith("get")) {
            m = (Method[]) ArrayUtils.remove(m, i);
        }
    }

    for (int i = 0; i < m.length; i++) {
        try {
            Object[] obj = {};
            String key = m[i].getName().substring(3);
            cl = Class.forName("com.nttdata.tbridge.platformmonitoring.configuration.Configuration");

            map.put(key, m[i].invoke(new Configuration(), obj).toString());


        } catch (Exception e) {

            e.printStackTrace();
        }

    }

    request.setAttribute("map", map);

    this.getServletContext().getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);

}

}

this servlet help to print on my browser files contain of my application. Applying reflection on a class in my project that i call "Configuration" which contains functions for files reading. it seems i'm missing something in invoke() function ? Someoe can help me ? the error edit is the following:

java.lang.IllegalArgumentException: wrong number of arguments
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 can I get a form reference from a class by name using reflection in C#?

I have a public static class called Router with some form references like this;

public static class Router
{
     static frmLogin rLogin = new frmLogin();
     static frmDashboard rDashboard = new frmDashboard();
     static frmReport rReport new frmReport();
}

I am trying to create a function called "Route" - this function will take a string parameter, which will match at least one of those form references. When matched, the selected form will have its "Index()" method invoked. (Every form has an Index() pre-built, I just need it called)

There's not too much to say about the purpose of this other than the fact that I'm creating an MVC-like structure for a very specific reason. So any other suggestions may be appreciated.


To summarise, I need to find the correct Form reference by name i.e. "rLogin" using a parameter passed into the "Route" method, which will eventually call the "Index()" function on that form.

I understand this may be possible with Reflection and I got a bit confused with other examples.

Thanks.





Getting DefaultValue for optional Guid through reflection?

I have the following code:

    public static void MethodWithOptionalGuid(Guid id = default(Guid)) { }

    public static void MethodWithOptionalInteger(int id = 2) { }

    public static void MethodWithOptionalString(string id = "33344aaa") { }

    public static void MethodWithoutOptionalParameter(int id, Guid longId) { }

    static void Main(string[] args)
    {
        var methods = typeof(Program).GetMethods(BindingFlags.Public | BindingFlags.Static).ToList();

        foreach (var method in methods)
        {
            PrintMethodDetails(method);
        }

        Console.ReadLine();
    }

    static void PrintMethodDetails(MethodInfo method)
    {
        Console.WriteLine(method.Name);

        foreach (var parameter in method.GetParameters().ToList())
        {
            Console.WriteLine(parameter.Name +
                              " of type " + parameter.ParameterType.ToString() +
                              " with default value:" + parameter.DefaultValue);
        }

        Console.WriteLine();
    }

It prints the following:

MethodWithOptionalGuid
id of type System.Guid with default value:

MethodWithOptionalInteger
id of type System.Int32 with default value:2

MethodWithOptionalString
id of type System.String with default value:33344aaa

MethodWithoutOptionalParameter
id of type System.Int32 with default value:
longId of type System.Guid with default value:

My question is: why the Guid's default value is not recognized?

I expected to receive something like "0000000-..." . I also tried initializing the optional parameter with new Guid() and same result. I tried as well other structs, like TimeSpan and the behavior is the same.

I expected that all value types would behave the same (as seen in integer example).





Add an anonymous subclass object to a base class list

I have a base class (Baseclass) from which I derived some subclasses (Subclass1, Subclass2, etc.). For each subclass, I want:

  • call the constructor with 'fixed' arguments (arg1, arg2, etc.);
  • check if the instantiation is valid (supposing to have a common method IsValid); and
  • add the instantiation to a list of object.

Here follows the excerpt of the code:

subclassList = new List<Type>()
{
   typeof(Subclass1),
   typeof(Subclass1),
   ...
};
List<Baseclass> objectList = new List<Baseclass>();
foreach (Type subclass in subclassList)
{
   ConstructorInfo[] constructorArray = subclass.GetConstructors(BindingFlags.Public);
   object o = constructorArray[0].Invoke(new object[] { arg1, arg2, ... });
   if (((Baseclass)o).IsValid)
   {
      objectList.Add(Convert.ChangeType(o, subclass));
   }
}





Limit a lambda expression to a simple property

The signature of my method is

void Sample<TData>(Expression<Func<TData,TValue>> expression) { }

I want to allow calls like:

Sample <MyData>(m => m.SomeProperty);

But not

Sample<MyData>(m => m.ComplexProperty.AnotherProperty);

I tried to count the number of nested bodies and limit the expression to those with a nesting count of 1, but this fails when 'SomeProperty' is derived from a base class.

private static int ItemCount(Expression lambaExpression)
{
    int itemCount = 0;
    var member = lambaExpression as MemberExpression;
    while (member != null)
    {
        itemCount += 1;
        member = member.Expression as MemberExpression;
    }
    return itemCount;
}

My question is: How do I distinguish between 'Foo.Bar' and 'Foo.Bar.Bar'?





mardi 22 mars 2016

Entity Framework - Determine the HasDatabaseGeneratedOption setting for a given type

For some of the properties in my DB I need to manually calculate their Id #, so for those properties I do .Property(p => p.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None); inside OnModelCreating

Then, in the repository I have a method to calculate out the Id for a given type. I would prefer to have the system be intelligent and check to see if the DatabaseGeneratedOption.None or DatabaseGeneratedOption.Identity and either return the next Id or 0.

How can I check (from inside a repository) what the DatabaseGeneratedOption for a given type (T) is?





Swift Tuple get named parameters

If I have an enum as below:

enum TempEnum {    
    case AAA(name:String, age:Int)
    case BBB(country:String)
    case CCC
}

I want to be able to for each case generate a dictionary of the associated parameters for each case. I don't want to to a switch!

If I execute this code:

let aaa = TempEnum.AAA(name: "bobby", age: 10)
let mirror = Mirror(reflecting: aaa)
var labels = [String]()
var values = [Any]()
for (label, value) in mirror.children {
    for (label, value) in Mirror(reflecting: value).children {
        labels.append(label!)
        values.append(value)
    }
}

Labels is: [".0", ".1"]

Values is: ["bobby", 10]

Is there any way to retrieve the actual named parameters (if they do exist), so that Labels is ["name", "age"]





Get All Properties name of a class without Reflection How?

I want to know Can I use Compiled Expressions for getting all property names of a class or not ?

I want a better method for getting property names instead of Reflection.

I need a way with best speed and performance. Of course, as far as possible

please guide me.





Incosistent conversion from object to string

I have a decimal? property called Balance in a class. I have two objects of this class and value for Balance in both object is same (let's say 100). I use reflection to get value of Balance from both objects like this

object bal1= type.GetProperty("Balance").GetValue(object1);
object bal2= type.GetProperty("Balance").GetValue(object2);

When I convert the object to string then I get different values.

Console.WriteLine(bal1.ToString()); // output : 100.00
Console.WriteLine(bal2.ToString()); // output : 100

Can someone explain what is the reason behind this?





Whats the purpose of the primitive getter/setter in Field?

In the documentation for public Object get(Object obj) method in the Field class it is stated that

The value is automatically wrapped in an object if it has a primitive type.

and for public void set(Object obj, Object value) that

If the underlying field is of a primitive type, an unwrapping conversion is attempted to convert the new value to a value of a primitive type.

So am I right that the only purpose of the specific primitive getter and setter like getInt and setInt is to prevent a redundant type conversion?
Since this code works fine

public class Test{  
    int i = 1;
    public static void main(String[] args) throws Exception{
        Test inst = new Test();
        Class<?> clazz = inst.getClass();
        Field fi = clazz.getDeclaredField("i");
        int ii = (int) fi.get(inst);
        Integer iii = new Integer(ii * 2);
        fi.set(inst, iii);
    }
}

I am asking if someone knows a scenario that needs you to use these methods aside from performance reasons.





C# Reflection of a class field

I searched but didn't find correct answer..

Assume that we have a class like:

public sealed Class Foo{
     public static readonly x;
     public static readonly y;
     public static readonly z;
     public static readonly t;

     public string Name{get;}
     public int Value{get;}
     public Foo(string name,int val){//properties sets here}
} 

And I have a Enum class like:

Public Enum FooFinder{
         x,
         y,
         z,
         t

}

this Foo class in a different library called FooLib.dll and FooFinder created by me..

I want to return Foo.x, Foo.y types using my enum class.

 private static Foo GetFoo (FooFinder Level)
    {
        FieldInfo[] props = typeof(Foo).GetFields();

        foreach (FieldInfo item in props)
        {

            if (item.Name == Enum.GetName(typeof(FooFinder), Level))
            {
                 //I could create an instance of Foo with Activator.CreateInstance() but I want to return Foo class' chosen field by FooFinder enum
            }
        }

    }

I hope I could explain what I want to do.. So how can I get Foo class' chosen field by reflection? or Can I get ?

Best Regards, Cagdas





Determining that interface is NOT implemented

Interface i1
End Interface

Public Class c1
    Implements i1
End Class

Public Class c2
    Inherits c1
End Class

How to determine (using reflection) that c2 have not implemented i1 ?





getDeclaredMethod leading to java.lang.NoSuchMethodException

In one of my classes i have put below lines of code to call the preOTPOperations of BLH class

Class<?> clazz = Class.forName("com.test.BLH");
Object obj = clazz.newInstance();
Class<?>[] paramTypes = new Class[4];
paramTypes[0]=String.class;
paramTypes[1]=String.class;
paramTypes[2]=Integer.class;
paramTypes[3]=COConfig.class;
Method m = clazz.getDeclaredMethod("preOTPOperations", paramTypes); 
String responseMessage = (String) m.invoke(obj, new Object[]{cardnumber, null, bankId, myConfig});

But, i get java.lang.NoSuchMethodException, when i try to invoke preOTPOperations method of BLH as above using invoke().

In BLH class i have preOTPOperations as below.

public String preOTPOperations(String cardnumber, String mobileNumber, int bankid, COConfig coConfig){

    //some code goes here

}

Not sure why i am getting NoSuchMethodException in spite of having preOTPOperations in BLH class with public access specifier. Someone kindly suggest the solution. Am i missing something? Thanks in advance!





lundi 21 mars 2016

NullPointer when using reflection to invoke a static method

I am trying to invoke a private static method declared in a Class .

Method method = Class.getDeclaredMethod("isResourcePotentiallyOnPath" , new Class[]{String.class, List.class});

method.setAccessible(true);

and then,

Object [] args = new Object[2];
args[0] = "SomeResource"
args[1] = null; //by default i want to pass in null here

boolean returnValue = (Boolean)method.invoke(null, args);

I see that method is not null but method.invoke causing null pointer somewhere down the stack

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)

What am i doing wrong??

Thanks





how to use activate.createinstance on 2d string array in reflection

Hi good people of SO,

I am facing a little challenge here and I can't quite figure it out. So I have a 2d array that I've created using the following :

var portTypes = assembly.GetExportedTypes();
string[,] commonIPPort= new string [2,2];
foreach (var v in portTypes )
        {
            if (v.FullName == "iControl.CommonIPPortDefinition")
            {
                commonIPPort= new string[,] { { v.Name, v.FullName }};
            }
        }
dynamic ports= Array.CreateInstance(typeof(object),commonIPPort.Length); 

This is where I get the null error: object item;

for (int i = 0; i < commonIPPort.Length; i++)
        {
            item = Activator.CreateInstance(Type.GetType(commonIPPort[i,i+1]));

        }

so my question is how do you use createinstance on a 2d string?

thank you in advance.





when i use reflection to find the codesize cachesize datasize of installed applications

the method onGetStatsCompleted(PackageStats pStats, boolean succeeded) the second parameter succeeded return false :( enter image description here

enter image description here

help! guys!





How to change method name at runtime in Java?

I have only one method which is getting invoked multiple time based on the parameters. I just want to append a string to the method name for each parameter at rudiment, so that it will help me in creating reports. Let’s take an example: public void InvokeMethod(string para) { enter code here // code we want to execute }

I want change the name of above method at run-time for each parameter. Please share your comments.





Very slow Reflection (trying to write a generic wrapper)

I'm trying to write a generic method to wrap an SDK we're using. The SDK provides "AFElement" objects that represent our data object, and each data AFElement has a collection of "AFAttributes" that map to our data objects' properties.

I've created a generic method which uses reflection to check the object it's called for's properties and get them (if they exist) from the AFElement.Attributes:

private T ConvertAFElementTo<T>(AFElement element, T item) where T : class, new()
{
    PropertyInfo[] properties = item.GetType().GetProperties();
    foreach (PropertyInfo property in properties)
    {
        //Get the Attribute object that represents this property
        AFAttribute attribrute = element.Attributes[property.Name];
        if (attribrute != null)
        {
            //check if we have the same type
            if (property.PropertyType.Equals(attribrute.Type))
            {
                //set our property value to that of the attribute
                var v = attribrute.GetValue().Value;
                property.SetValue(item, v);
            }
            //check if we have an AFElement as an Attribute that will need converting to a data object
            else if (attribrute.Type.Equals(typeof(AFElement)))
            {
                AFElement attributeElement = attribrute.GetValue().Value as AFElement;
                Type attributeType = null;

                //look up it's data type from the template
                TypeConversionDictionary.TryGetValue(attributeElement.Template, out attributeType);

                if (attributeType != null)
                {
                    //set it as a .NET object
                    property.SetValue(item, ConvertAFElementTo(attributeElement, Activator.CreateInstance(attributeType)));
                }
            }
        }
    }
    return item;
}

The idea is I can throw any of my data objects T at this method and it would populate them, and it works, except it's exceptionally slow.

It takes around 10 seconds to get 63 objects, 93% of the time is in this conversion method. I've heard reflection wasn't very efficient, but is is this inefficient?

Is there any other way I could do this, or a way to speed things up? Am I being stupid even trying to do something this generic?





Is Method.invoke broken in java8?

I just created the following minimalistic testcase:

package testcase;

public class Main
{

    public static void main( String[] args )
        throws Throwable
    {
        if ( args.length == 0 )
            Main.class.getMethod( "main", String[].class ).invoke( null, new String[] { "test" } );
    }

}

It should just run, with no output and no exception. The main method should be calling itself using reflection. However I get the following exception:

Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at testcase.Main.main(Main.java:10)

And I cannot figure out, why...





Null Pointer Exception while using Reflection

I'm following a tutorial for Selenium - Keyword Driven Framework here. I'm not very familiar with the the Reflection API. (I'm a beginner to Java as well)

When I execute my main class, I'm receiving a Null Pointer Exception. I'm not sure what I'm doing wrong. Might be a silly mistake. Please help me understand what I'm missing here. (Also, if someone can guide me where I can learn better about Keyword Driven Framework and the Reflection API from a beginner's standpoint, that would be very helpful.)

DriverScript:

package testdev;

import java.lang.reflect.Method;
import config.ActionKeywords;
import utility.ExcelUtils;

public class DriverScript {

public static ActionKeywords actionKeywords;
public static String sActionKeyword;
public static Method method[];

public DriverScript() throws NoSuchMethodException, SecurityException{
    actionKeywords = new ActionKeywords();
    method = actionKeywords.getClass().getMethods();
}

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

    String sPath = "C://Users//testusr//workspace//src//datasource//datasource.xlsx";
    ExcelUtils.setExcelFile(sPath, "sheet");

    for(int i=1; i<=7; i++){
        sActionKeyword = ExcelUtils.getCellData(i, 3);
        execute_Actions();
    }
}

private static void execute_Actions() throws Exception{

    for(int j=0;j < method.length;j++){
        if(method[j].getName().equals(sActionKeyword)){
            method[j].invoke(actionKeywords);
            break;
        }
    }

}
}

ActionKeywords:

package config;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ActionKeywords {

public static WebDriver driver;

public static void openbrowser(){
    System.setProperty("webdriver.chrome.driver", "G:\\Ram\\MAC\\Se\\chromedriver.exe");
    driver = new ChromeDriver();
}

public static void navigate(){
    driver.get("http://ift.tt/1XGzuHR");
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.manage().window().maximize();
}

public static void enter_credentials(){
    driver.findElement(By.id("login-form-username")).sendKeys("RMuruganandam");
    driver.findElement(By.id("login-form-password")).sendKeys("jan@2016");
}

public static void click_login(){
    driver.findElement(By.id("login")).click();
}

public static void wait_for(){
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}

public static void click_logout() throws InterruptedException{
    driver.findElement(By.id("header-details-user-fullname")).click();
    Thread.sleep(30);
    driver.findElement(By.id("log_out")).click();
}

public static void closebrowser(){
    driver.quit();
}

}

ExcelUtils:

package utility;

import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils {

public static XSSFWorkbook ExcelWBook;
public static XSSFSheet ExcelWSheet;
public static XSSFCell Cell;
public static FileInputStream ExcelFile;

public static void setExcelFile (String Path, String SheetName) throws Exception{
    FileInputStream ExcelFile = new FileInputStream(Path);
    ExcelWBook = new XSSFWorkbook(ExcelFile);
    ExcelWSheet = ExcelWBook.getSheetAt(0);
}

public static String getCellData (int rowNum, int colNum) {
    String CellData ="";
    Cell = ExcelWSheet.getRow(rowNum).getCell(colNum);
    CellData= Cell.getStringCellValue();        
    return CellData;
}
}





Instantiating all classes that extend trait in Scala

So I'm building a library, and the problem I have is as follows:

I have a trait, such as

trait Animal {
  def randomFunctions
}

What I need to know is all the classes the library's user has, that extend said trait, such as

case class Cat extends Animal
case class Dog extends Animal

And as I said those subclasses wouldn't be included in the library which contains the trait (and where I need to work my magic)





dimanche 20 mars 2016

Java Reflection into Lamba expressions

Lets assume i have this very very simple code. What I want is to convert it into Lambda expressions explicitly.

Here is the code:

import java.lang.reflect.Method;

public class test {

    float decrement = 1f;
    float speed = 0.15f;

    public test() {
        for (;;) {
            run();
        }
    }

    private void run() {

        try {
            update(this.getClass().getMethod("print"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void update(Method myCustomMethod) throws Exception {

        if (decrement <= 0) {

            myCustomMethod.invoke(this);

            decrement = 1f;
        } else {
            decrement -= speed; // 1 * 0.15 = 
            System.out.println(decrement);
        }

    }

    public void print() {
        System.err.println("something");
    }

}

How will i go about converting the Java reflection parts into pure lambda expressions?





Using Reflection in .NET Core

I'm trying to make a .NET Core shared library. I used the Class Library (package) project template in VS 2015. My library needs to use a couple reflection mechanisms I am familiar with from the full .net 4 framework, but I don't now how to access these in a .NET Core library. Specifically:

  • The Delegate type has a Method property that returns a MethodInfo object.
  • The Type class has a BaseType property, FilterName property, InvokeMember method and FindMembers method I can't reach in .NET Core.

I added NuGet packages that allegedly have the reflection pieces I need:

"frameworks": {
  "net451": {
    "dependencies": {
      "System.Reflection": "4.1.0-beta-23516",
      "System.Reflection.Extensions": "4.0.1-beta-23516",
      "System.Reflection.Primitives": "4.0.1-beta-23516",
    }
  },
  "dotnet5.4": {
    "dependencies": {
      "Microsoft.CSharp": "4.0.1-beta-23516",
      "System.Collections": "4.0.11-beta-23516",
      "System.Linq": "4.0.1-beta-23516",
      "System.Reflection": "4.1.0-beta-23516",
      "System.Reflection.Extensions": "4.0.1-beta-23516",
      "System.Reflection.Primitives": "4.0.1-beta-23516",
      "System.Runtime": "4.0.21-beta-23516",
      "System.Threading": "4.0.11-beta-23516"
    }
  }
},
"dependencies": {
  "System.Reflection.TypeExtensions": "4.1.0-beta-23516"
}

I've also added using System.Reflection, but I still am getting errors that indicate that these properties and types are undefined.

What am I doing wrong?





Java Reflection (unsure on how to word this, look inside for more info)

I need to make a Deep Copy of a 2D array. I know how to do this

int[][] a = new int[original.length][];
for(int i = 0; i < original.length; i++) {
    a[i] = Arrays.copyOf(original[i], original[i].length);
}

However, I'm now in a position where I don't know the Object type of the Array I'm copying. I have a method like so

public Object[] copy(Object[] original) {}

Which should return a deep copy of original IF it is an array of arrays. If the method is given a int[][], I can't cast that to an Object for the array (since it's a primitive type).

Currently, I can check to see if 'original' is a 2D array like so

if(original==null||original.length==0||!original.getClass().getName().startsWith("[")) {
    return null;
}

But now I'm unsure on how to do a Deep copy of an array of an unknown type. I assume I'll be needing to use Java Reflection, although I'm not 100% sure on how I would go about this.





Using reflection to test that all collection properties of classes will be instantiated

I'm trying to craft a unit test that will check for a given assembly that all non-abstract classes with empty constructors will instantiate their collection properties when instantiated. Here's the system under test:

namespace MyProject.Dto.Things
{
    public class Item
    {
        public Item()
        {
            // Second batch of props should be instantiated here...
        }

        // Properties that my test doesn't/shouldn't care about:
        public int IntProp { get; set; }
        public string StringProp { get; set; }

        // Properties my test should account for:
        public List<string> ListProp { get; set; }
        public IList<string> IListProp { get; set; }
        public ISet<string> ISetProp { get; set; }
        public ICollection<string> ICollectionProp { get; set; }
        public IDictionary<string, string> IDictionaryProp { get; set; }
        public Stack<string> StackProp { get; set; }
        public string[] ArrayProp { get; set; }
    }
}

My first attempt whas this:

[TestFixture]
public class DtoTests
{
    [Test]
    public void NamespaceDtos_WhenDefaultConstructorIsCalled_InstantiatesCollectionProperties()
    {
        bool testWasMeaningful = false;

        foreach (var type in GetEntityTypesWithDefaultConstructor())
        {
            var instance = Activator.CreateInstance(type);
            var collectionProps = type
                .GetProperties()
                .Where(p => typeof(ICollection<>).IsAssignableFrom(p.PropertyType));

            foreach (var prop in collectionProps)
            {
                var val = prop.GetValue(instance);
                Assert.That(val, Is.Not.Null.And.Empty, string.Format("[{0}.{1}]", type.Name, prop.Name));
                testWasMeaningful = true;
            }
        }

        Assert.That(testWasMeaningful, "Expected at least one assertion.");
    }

    private IEnumerable<Type> GetEntityTypesWithDefaultConstructor()
    {
        return Assembly
            .GetAssembly(typeof(MyProject.Dto.Things.Item))
            .GetTypes()
            .Where(t => !t.IsAbstract)
            .Where(t => t.GetConstructor(Type.EmptyTypes) != null);
    }
}

However, this does not work, because the Where clause does not grab the correct properties from my other assembly. My test fails because it tests not a single property.


Attempted fix no 1

I've tried this answer like this:

var collectionProps = type
    .GetProperties()
    .Where(m => m.PropertyType.IsGenericType && m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>));

But that only catches Item.ICollectionProp, and fails to test all others.


Attempted fix no 2

Second, I've tried this answer to another question (using the GetICollectionOrICollectionOfTProperties method ad verbatim), like this:

var collectionProps = type
    .GetICollectionOrICollectionOfTProperties();

But ironically, that will incorrectly pass the test even if Item.ICollectionProp is not instantiated.


Attempted fix no 3

I've also tried testing just all IEnumerable properties, like this:

var collectionProps = type
    .GetProperties()
    .Where(p => typeof(IEnumerable).IsAssignableFrom(p.PropertyType));

But that will fail on Item.StringProp, because string is IEnumerable, and I do not want to test for that here.


I'm not sure where I go wrong, especially with nr 2. I'd even think my question is a duplicate of that one, if I'd only had gotten the solution to work.

Bottom line: (X) how can I test that all collection properties of classes with empty constructors are instantiated when the class is instantiated, and/or (Y) how can I find all collection properties of a type using reflection?