vendredi 31 janvier 2020

How to type assert a dynamically reflection-generated struct interface

I'm new to Go so please bear with me if this is a trivial problem. I am using a home grown "type registry" to map type names to their type, so as to generate them dynamically based on use cases that point to the various type names (I'm basically trying for a simple solution to polymorphic Aggregation JSON response structures in Elasticsearch, but of course this could apply to many other dynamic/polymorphic situations). I'm using the solution provided by dolmen in this question: is there a way to create an instance of a struct from a string? :

var typeRegistry = make(map[string]reflect.Type)

func registerType(typedNil interface{}) {
    t := reflect.TypeOf(typedNil).Elem()
    typeRegistry[t.Name()] = t
}

func init() {
    registerType((*playlistIDAggregation)(nil))
    registerType((*srcIDAggregation)(nil))
    registerType((*assetIDAggregation)(nil))
}

func makeInstance(name string) interface{} {
    return reflect.New(typeRegistry[name]).Elem().Interface()
}

I then want to use my dynamically generated struct as the target for the JSON unmarshalling of the Aggregations node in my ES response:

playlistIDAgg := makeInstance("playlistIDAggregation")
err = json.Unmarshal(esResponse.Aggregations, &playlistIDAgg)

This isn't working like I want it to, as the Unmarshal is trying to unmarshall into an empty interface instead of the underlying struct type. it's putting the data under "data" nodes in the playlistIDAgg variable, and those data fields are of course map[string]interface{}. Am I just missing the way to type assert my playlistIDAgg interface or is there a better way to do this?





Run-time indexing of tuple

Suppose I have a variable constructors, which is a tuple of constructor functions represented in variadic generic lambdas.

// types for constructors 
using type_tuple = std::tuple<ClassA, ClassB, ClassC>;

// Get a tuple of constructors(variadic generic lambda) of types in type_tuple
auto constructors = execute_all_t<type_tuple>(get_construct());

// For definitions of execute_all_t and get_construct, see link at the bottom.

I can instantiate an object with:

// Create an object using the constructors, where 0 is index of ClassA in the tuple.
ClassA a = std::get<0>(constructors)(/*arguments for any constructor of ClassA*/);

Is it possible to index the type in runtime with a magic_get like below?

ClassA a = magic_get(constructors, 0)(/*arguments for any constructor of ClassA*/);

A minimal reproducible example: Try it online!





jeudi 30 janvier 2020

Finding a specific method via reflection

Let's say we have two public methods within a class:

public class SomeClass
{
    public bool DoSomething(int param1)
    {
        return param1 == 30;
    }

    public bool DoSomethingElse(int param1)
    {
        param1 *= 2;
        return param1 == 30;
    }
}

I could write the following code to get both of these methods using reflection:

MethodInfo[] methods = typeof(SomeClass).GetMethods(BindingFlags.Public | BindingFlags.Instance)
                       .Where(x => x.ReturnType == typeof(bool)
                              && x.GetParameters().Length == 1
                              && x.GetParameters()[0].ParameterType == typeof(int)).ToArray();

Let's say I only wanted DoSomethingElse, I could just use methods[1].

However, let's say they swapped places the next time this class is compiled. I would end up with DoSomething instead.

The only thing that separates these two methods, is that DoSomethingElse multiplies the parameters by 2 before checking.

Are there any other checks I can do with reflection to ensure I always get DoSomethingElse?

Note: The methods I'm looking for may have their names changed each time it is compiled, so simply searching for their name won't work either.





How do JSP pages find the correct setters for parameters

Say I have the following JSP page:

<jsp:useBean id="bean" scope="page" class="com.test.jsp.beans.TestBean"/>
<jsp:setProperty name="bean" property="*"/>
...
<input type="text" name="test" value="test value"/>
...

and the bean:

package com.test.jsp.beans;

public class TestBean {
    public String test;

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}

How does java know to pass the value from the <input> tag to the setTest() method?

I would like to understand the inner workings of how they are linked, I assume reflection is used.

Does java look for the setter method or does it look for the variable?

Does the setter name need to be set + <input> name?

Does the setter need to contain exactly one parameter?

Does that parameter need to be the same name as the <input> tag?

Does the setter even need parameters?

Does capitalization matter?

etc...





how to set value with reflection

I am writing J-unit test case for one my method.

A.java

 void resetToolbar(final ListSelectionModel lastSelectionModel) {
        // attempt to restore the previous page
        if (toolbar != null && lastSelectionModel != null) {
            gridPanel.setSelectionModel(lastSelectionModel);
        }
       // Issue occur here..... In PagingToolbar.
        toolbar = new PagingToolbar();
    }

PagingToolbar.java

class PagingToolbar {
private I18nUtils i18n;   //It is a class How should I mock these. i18n

/**
 * Creates a new paging toolbar.
 */
public PagingToolbar() {
    super();
    setDisplayingItemsText(i18n.getText(this, "facebook")); 
// here i18n get null and throws null pointer-exception.

}

ATest.java

@Test(groups = { "unit" })
public class ATest {
    @Test
    public void resetToolbar(){

        I18nUtils i18n = createNiceMock(I18nUtils.class);

        // Invoke
        A tt = new A();

        // How to set i18n with reflection in pagingToolbar.
        tt.resetToolbar(listselectmodelMock);
    }
}

NOTE : In A class in resetToolbar() , I have to invoke pagingToolbar with new keyword.





mercredi 29 janvier 2020

Include file with namespace in PHP terminates script unexpectedly

I started off by trying to include every file in a GitHub project. My purpose is to call get_declared_classes() after that as a form of reflection so I can learn what classes are declared in the project. Never did I expect that I would run into this problem which I have no solution for after much research and testing. Please help.

The project I am using: https://github.com/farafiri/PHP-parsing-tool

I downloaded it into a folder. Wrote this code:

$toparse = shell_exec("find '/Users/user/Documents/PHP-parsing-tool-master/src' -iname '*.php' 2> /dev/null");
$filenames = explode("\n", $toparse);
//d() is a custom function that acts like var_dump.
d($filenames);

$filenames dumps (please pardon the custom format that comes with d(). Basically $filenames is an array of 77 elements with each element a string representing paths of each file in the Github project):

array (77) [
    0 => string (77) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/RuleCondition.php"
    1 => string (76) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/SequenceItem.php"
    2 => string (71) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/Integer.php"
    3 => string (70) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/Series.php"
    4 => string (68) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/Time.php"
    5 => string (69) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/Regex.php"
    6 => string (105) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/ItemRestrictions/ItemRestrictionInterface.php"
    7 => string (98) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/ItemRestrictions/ItemRestrictionOr.php"
    8 => string (99) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/ItemRestrictions/ItemRestrictionAnd.php"
    9 => string (91) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/ItemRestrictions/FollowedBy.php"
    10 => string (83) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/ItemRestrictions/Is.php"
    11 => string (88) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/ItemRestrictions/Contain.php"
    12 => string (99) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/ItemRestrictions/ItemRestrictionNot.php"
    13 => string (72) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/TextNode.php"
    14 => string (86) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/WhiteCharactersContext.php"
    15 => string (82) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/ExtensionInterface.php"
    16 => string (70) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/Choice.php"
    17 => string (80) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/ItemRestrictions.php"
    18 => string (68) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/Base.php"
    19 => string (73) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/Lookahead.php"
    20 => string (80) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/ParametrizedNode.php"
    21 => string (71) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/Unorder.php"
    22 => string (68) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/Text.php"
    23 => string (76) "/Users/user/Documents/PHP-parsing-tool-master/src/Extension/StringObject.php"
    24 => string (70) "/Users/user/Documents/PHP-parsing-tool-master/src/ParsingException.php"
    25 => string (60) "/Users/user/Documents/PHP-parsing-tool-master/src/Parser.php"
    26 => string (64) "/Users/user/Documents/PHP-parsing-tool-master/src/Util/Regex.php"
    27 => string (64) "/Users/user/Documents/PHP-parsing-tool-master/src/Util/Error.php"
    28 => string (75) "/Users/user/Documents/PHP-parsing-tool-master/src/SyntaxTreeNode/Series.php"
    29 => string (85) "/Users/user/Documents/PHP-parsing-tool-master/src/SyntaxTreeNode/PredefinedString.php"
    30 => string (75) "/Users/user/Documents/PHP-parsing-tool-master/src/SyntaxTreeNode/Branch.php"
    31 => string (73) "/Users/user/Documents/PHP-parsing-tool-master/src/SyntaxTreeNode/Base.php"
    32 => string (76) "/Users/user/Documents/PHP-parsing-tool-master/src/SyntaxTreeNode/Numeric.php"
    33 => string (73) "/Users/user/Documents/PHP-parsing-tool-master/src/SyntaxTreeNode/Root.php"
    34 => string (73) "/Users/user/Documents/PHP-parsing-tool-master/src/SyntaxTreeNode/Leaf.php"
    35 => string (77) "/Users/user/Documents/PHP-parsing-tool-master/src/SyntaxTreeNode/LeafTime.php"
    36 => string (71) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNodeCopier.php"
    37 => string (72) "/Users/user/Documents/PHP-parsing-tool-master/src/Examples/CSVParser.php"
    38 => string (88) "/Users/user/Documents/PHP-parsing-tool-master/src/Examples/YamlLikeIndentationParser.php"
    39 => string (89) "/Users/user/Documents/PHP-parsing-tool-master/src/Examples/ArithmeticExpressionParser.php"
    40 => string (73) "/Users/user/Documents/PHP-parsing-tool-master/src/Examples/JSONParser.php"
    41 => string (75) "/Users/user/Documents/PHP-parsing-tool-master/src/Examples/JSONFormater.php"
    42 => string (86) "/Users/user/Documents/PHP-parsing-tool-master/src/Examples/BooleanExpressionParser.php"
    43 => string (74) "/Users/user/Documents/PHP-parsing-tool-master/src/ParserAwareInterface.php"
    44 => string (63) "/Users/user/Documents/PHP-parsing-tool-master/src/Exception.php"
    45 => string (72) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/Series.php"
    46 => string (75) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/PEGBranch.php"
    47 => string (96) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/WhitespaceNegativeContextCheck.php"
    48 => string (81) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/BranchInterface.php"
    49 => string (74) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/BaseNode.php"
    50 => string (82) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/PredefinedString.php"
    51 => string (79) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/LeafInterface.php"
    52 => string (71) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/Regex.php"
    53 => string (86) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/BranchExtraCondition.php"
    54 => string (79) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/BranchFactory.php"
    55 => string (79) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/ParameterNode.php"
    56 => string (73) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/AnyText.php"
    57 => string (72) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/Branch.php"
    58 => string (72) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/Choice.php"
    59 => string (82) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/ItemRestrictions.php"
    60 => string (75) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/Decorator.php"
    61 => string (73) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/Numeric.php"
    62 => string (75) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/Lookahead.php"
    63 => string (82) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/ParametrizedNode.php"
    64 => string (87) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/BranchStringCondition.php"
    65 => string (79) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/NodeInterface.php"
    66 => string (88) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/WhitespaceContextCheck.php"
    67 => string (88) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/PredefinedSimpleString.php"
    68 => string (77) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/NaiveBranch.php"
    69 => string (73) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/Unorder.php"
    70 => string (81) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/BranchDecorator.php"
    71 => string (74) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/LeafTime.php"
    72 => string (70) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/Text.php"
    73 => string (71) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/TextS.php"
    74 => string (85) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarNode/ErrorTrackDecorator.php"
    75 => string (67) "/Users/user/Documents/PHP-parsing-tool-master/src/GrammarParser.php"
    76 => string (0) ""
]

Then:

foreach ($filenames as $n=>$f) {

    d($f);
    include $f;
    d($f);

}

The foreach loop has no issue up till the element with index 15. The script terminates when including that file. I know this because the d() function before the include was executed, but not the d() function after the include. I ran the script on the command line, and used PHP7.2.10, from MAMP 4, on macOS 10.13.6.

This is the full contents of that file:

   <?php

    namespace ParserGenerator\Extension;
    echo "hello in interface";

    interface ExtensionInterface
    {
        function extendGrammar($grammarGrammar);

        function modifyBranches($grammar, $parsedGrammar, $grammarParser, $options);

        function createGrammarBranch($grammar, $grammarBranch, $grammarParser, $options);

        function fillGrammarBranch($grammar, $grammarBranch, $grammarParser, $options);

        function buildSequenceItem(&$grammar, $sequenceItem, $grammarParser, $options);

        function buildSequence($grammar, $rule, $grammarParser, $options);
    }

    echo "hello in interface 2";

The script terminated after "hello in interface" was echoed. "hello in interface 2" was never echoed.

The strange thing is also that even though my php.ini file has already been set to error_reporting=E_ALL and display_errors=On, no information on the script termination whatsoever was dumped to my terminal. There's no parse error, fatal error etc.

What is the problem and how do I make the script execute all the way to the end? Apologies, but am I missing something on namespaces and interfaces?





How to configure proguard + reflection?

How to configure proguard if almost all classes use reflection and need to obfuscate such classes? Is there such an opportunity? Reflection is used for logging using logaspect





Accessing NHibernate ActionQueue to check the list of pending commands

I have some very basic code:

NHibernate.ISession session = doSomeStuffWithNHibernateSession();

Using the object inspector in the Visual Studio debugger, I am able to open the ActionQueue of the session object and list all the pending NHibernate commands.

Is there a way to access it programmatically ? Being able to access properties like InsertionCount or HasAnyQueuedAction would be enough.





java.lang.NoSuchMethodError after system is running for multiple hours

Assume a public Class A

public class A {

    public boolean test(Object a) {
        return true;
    }

}

and let this method invoke via

java.lang.Class.forName("A").getMethod(test, Object.class).invoke(new A(), new Object());

This routine works during Application's runtime 24/7 but seems to fail non-deterministic. It throws a NoSuchMethodError.

Do you have any idea, why this method will fail from one timepoint to another?

We use the java 8 version from open jdk project and run the application in suse enterprise 14.0.4 and this server was up and running without any hint of interruption.

After restarting the application without any changes on the jar the function invokation works perfectly fine again.





Infer generic types based on expression

I am building a DSL in C# using expression trees and one of the challenges I am trying to solve is inferring generic types from an input expression. Here is a contrived example:

class GenericThing<T> {
    public List<IOption<T>> solveMe;
}

// given the type of some expression, (and assuming types are assignable to each other)
var someExpression = new List<IOption<string>>();

// call a function that can infer the type of generic arguments from `GenericThing<>`
Type reflected = SolveGenericTypes(typeof(GenericThing<>), "solveMe", someExpression.GetType()));

// use that type to create an instance of GenericThing<string>
object instance = Activator.CreateInstance(reflected);

How could I implement SolveGenericTypes() to 'solve' for T? (Bonus, also solve for multiple generic arguments) I would need the function to work not just for this case, but basically take any generic type definition and any concrete type (assume there are no typechecking errors) and return a type that can be instantiated.

Thanks!





reflection - get type of single slice element

I want to iterate over struct definition recursively and for slices get a type of a singular element. Then, create an empty instance of that type. For example:

type Path struct {
  Name string
  Points []Coordinate
}
type Coordinate struct {
  Latitude float64
  Longitude float64
}

Assuming that types are unknown at runtime, how can I create an empty instance of the nested type (in the above example Coordinate). I mean:

x := Coordinate{}

When at input I get Path (which can be any other struct, with slices of different types)?





mardi 28 janvier 2020

Android Get Calling class fields

I have an android application that call my method via DexClassLoader loadClass and invoke().

I need to access the fields of the class that call my method from my method itself.

I managed to get the name of the calling method via the Stack Trace but I already know that so it's not useful and I don't manage to access the class itself from the stack trace, only his name...

Do you have an idea on how could I be able to get the value of the fields of the calling class from the method I control ?

I think there is a Reflection class that could be able to do that in basic java but I can't find something like that on android...

Thanks





C# Dynamically retrieve value of property

I am trying to get the data type of a property dynamically in my app. I have the following line of code using the name of the backing variable for the property to get the type and it works correctly.

var tobj_Type = this.GetType().GetField("ii_ServerPort", BindingFlags.Public | BindingFlags.Instance).GetValue(this).GetType();

In this line of code, I attempt to use the name of the property to try to get the type.

var tobj_PropertyType = this.GetType().GetField("ServerPort", BindingFlags.Public | BindingFlags.Instance).GetValue(this).GetType();

It fails with the following error: Object reference not set to an instance of an object.

Any idea how I can use the property name here instead of the backing variable?





Can i adding new child class at run time?

I need to add the following class at run time:

public class MapperFunction extends Mapper<Integer, String, String, Integer> {


    public MapperFunction(InputBlock s) {
        super(s);
    }

    @Override
    protected void map(Integer key, String value) {
        Pattern pattern = Pattern.compile("[a-zA-Z]+");
        Matcher matcher;
        String str = value;
        if (!str.equals("")) {
            matcher = pattern.matcher(str);
            while (matcher.find()) {
                String word = matcher.group();
                if (!MapperOut.containsKey(word))
                    MapperOut.put(word, 1);
                else
                    MapperOut.put(word, (Integer) MapperOut.get(word) + 1);
            }
        }
    }
}

or add the method map() to class during run time. i read the following question on stackoverflow Extending or adding new classes at runtime in Java but i think my case different a bit, any way this is the parent class Mapper:

public abstract class Mapper<keyIn, valueIn, keyOut, valueOut> extends Thread {

    private RecordReader recordReader;
    static AtomicInteger numberOfThreadsPerMapper = new AtomicInteger(2);
    static Map<Object, Object> MapperOut = null;

    static {
        MapperOut = Collections.synchronizedMap(new TreeMap<>());
    }

    Mapper(InputBlock s) {
        recordReader = new LineRecordReader(s);
    }

    protected abstract void map(keyIn key, valueIn value) throws IOException, InterruptedException;

    @Override
    public void run() {
        run2();
    }

    public void run2() {
        try {
            while (recordReader.hasNext()) {
                map((keyIn) recordReader.getKey(), (valueIn) recordReader.getValue());
            }
            //   System.out.println("Thread out." + numberOfThreads.getAndIncrement());
        } catch (Exception e) {
            // e.printStackTrace();
        }
    }
}

note that the parent class Mapper extends Thread my second question if i can do that how i can create instance from it, now this my call to create:

  @Override
    public void update(Observable o, Object arg) {

        executorService.submit(new MapperFunction((InputBlock) arg));
    }

my last questions if all that can be happen is there any disadvantages ?(performance issue)since the application create more instance from Mapper class?





Deep merging data classes in Kotlin

How can I do a recursive / deep merge of two data classes in Kotlin? Something like this:

import kotlin.reflect.*
import kotlin.reflect.full.*

data class Address(
  val street: String? = null,
  val zip: String? = null
)

data class User(
  val name: String? = null,
  val age: Int? = null,
  val address: Address? = null
)

inline fun <reified T : Any> T.merge(other: T): T {
  val nameToProperty = T::class.declaredMemberProperties.associateBy { it.name }
  val primaryConstructor = T::class.primaryConstructor!!
  val args = primaryConstructor.parameters.associate { parameter ->
    val property = nameToProperty[parameter.name]!!
    val type = property.returnType.classifier as KClass<*>
    if (type.isData) {
      parameter to this.merge(other) //inline function can't be recursive
    } else {
      parameter to (property.get(other) ?: property.get(this))
    }
  }
  return primaryConstructor.callBy(args)
}

val u1 = User(name = "Tiina", address = Address(street = "Hämeenkatu"))
val u2 = User(age = 23, address = Address(zip = "33100"))

u1.merge(u2)
// expected: User(age = 23, name= "Tiina", address = Address(zip = "33100", street = "Hämeenkatu")

related: Combining/merging data classes in Kotlin





Why a public static method is not accessible?

I'm trying to reflect the parse(CharSequence, DateTimeFormatter) methods from classes which each extends the TemporalAccessor class.

    private static final Map<Class<?>, MethodHandle> PARSE_HANDLES = synchronizedMap(new HashMap<>());

    static <T extends TemporalAccessor> MethodHandle parseMethodHandle(final Class<T> clazz) {
        if (clazz == null) {
            throw new NullPointerException("clazz is null");
        }
        return PARSE_HANDLES.computeIfAbsent(clazz, k -> {
            try {
                final Method method = clazz.getMethod("parse", CharSequence.class, DateTimeFormatter.class);
                log.debug("method: {}, {}", method, method.isAccessible());
                // i don't understand; public static method is not accessible? yet it isn't.
                assert method.isAccessible(); // NOT GOOD with UTs
                return MethodHandles.lookup().unreflect(method);
            } catch (final ReflectiveOperationException roe) {
                throw new RuntimeException(roe);
            }
        });
    }

With the YearMonth class, I got this.

method: public static java.time.YearMonth java.time.YearMonth.parse(java.lang.CharSequence,java.time.format.DateTimeFormatter), false

Why a public static method is not accessible?





lundi 27 janvier 2020

How to print member names and its value in c#? [duplicate]

I am trying to create a class with many public members. The number is large, so I don't want to print them one by one. Therefore, I want to use C# build-in functions to print out all member names and its value. The approach I tried was to use type.GetMembers() to get MemberInfo, which allowed me to get all of the member names. However, I still can't get values. The following is my source code:

public class Unit : Card
{
    // ... a bunch of public members
    public string name;
    // ... more
    // ...

    public void print()
    {
            Debug.Log("CARD INFO \"" + name + "\":\n");

            Type type = typeof(Unit);
            MemberInfo [] members = type.GetMembers();

            foreach(var member in members)
            {
                FieldInfo field = type.GetField(member.Name);
                Debug.Log(member + ": " + field.GetValue(this) );
            }

     }
}

This script is used by Unity, Debug.Log() is just used to output strings. The error I get is "Object reference not set to an instance of an object", referring to the last line of code. So I am guessing it could be due to the use of this. Any help is appreciated!





AbstractValidator load by model type

This question is related to FluentValidation nugetpackage

I have a Person model and an Address model and they both inherit from class called RecordTypeModel. I have fluent PersonValidator and AddressValidator. I then have a class called CreateFile(RecordTypeModel model).

RecordTypeModel class has a property called RecordType

In CreateFile() when model.RecordType is Person then I want to create PersonValidator instance. But I dont want to have a bunch of switch/ifelse statements.

I have tried this

var validator = GetValidatorInstance($"{item.RecordType}Validator") as AbstractValidator; 

enter image description here But AbstractValidator of fluentValidation package forces to provide exact model.





Openjdk openJ9 vs hotspot reflection difference using ZKOSS

I'm currently using a web application using the ZK (https://www.zkoss.org/) framework successfully using a HotSpot JVM (https://adoptopenjdk.net/?variant=openjdk11&jvmVariant=hotspot). Using this JVM, ZK can reflectively access my objects (beans) using its EL package. When I try running it with another standard-JVM (openj9 from https://adoptopenjdk.net/?variant=openjdk11&jvmVariant=openj9), reflectively accessing attributions of certain object lead to exceptions (see end of this message). I'd like to use this JVM as its memory footprint is smaller than hotspot for my application.

Is there any reason why a different JVM would lead to different results? If so, how should I troubleshoot it?

In this specific case, ZK uses a forked version of Apache Common EL, which is a discontinued project.(2003). The exception I get is listed below. Here, the framework has failed to access the object (application-level object, not java.lang.Long) in question, and is calling a method that does not exist on Long (but exists in application object).

org.zkoss.zel.PropertyNotFoundException: Property 'visible' not found on type java.lang.Long
at org.zkoss.zel.BeanELResolver$BeanProperties.get(BeanELResolver.java:424) ~[zel_8.6.2.jar:8.6.2]
at org.zkoss.zel.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:375) ~[zel_8.6.2.jar:8.6.2]
at org.zkoss.zel.BeanELResolver.property(BeanELResolver.java:547) ~[zel_8.6.2.jar:8.6.2]
at org.zkoss.zel.BeanELResolver.getValue(BeanELResolver.java:98) ~[zel_8.6.2.jar:8.6.2]
at org.zkoss.zel.CompositeELResolver.getValue(CompositeELResolver.java:66) ~[zel_8.6.2.jar:8.6.2]
at org.zkoss.zel.CompositeELResolver.getValue(CompositeELResolver.java:66) ~[zel_8.6.2.jar:8.6.2]
at org.zkoss.zel.CompositeELResolver.getValue(CompositeELResolver.java:66) ~[zel_8.6.2.jar:8.6.2]
at org.zkoss.xel.zel.XelELResolver.getValue(XelELResolver.java:99) ~[zcommon_8.6.2.jar:8.6.2]
at org.zkoss.bind.xel.zel.BindELResolver.getValue(BindELResolver.java:123) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.zel.impl.parser.AstValue.getValue(AstValue.java:188) ~[zel_8.6.2.jar:8.6.2]
at org.zkoss.zel.impl.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184) ~[zel_8.6.2.jar:8.6.2]
at org.zkoss.zkmax.bind.impl.ValueExpressionImplEx.getValue(ValueExpressionImplEx.java:52) ~[zkmax_8.6.2.jar:8.6.2]
at org.zkoss.xel.zel.ELXelExpression.evaluate(ELXelExpression.java:41) ~[zcommon_8.6.2.jar:8.6.2]
at org.zkoss.zkmax.bind.impl.BindEvaluatorXImplEx$LazyBindXelExpression.evaluate(BindEvaluatorXImplEx.java:124) ~[zkmax_8.6.2.jar:8.6.2]
at org.zkoss.bind.impl.BindEvaluatorXImpl.getValue(BindEvaluatorXImpl.java:46) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.bind.impl.LoadPropertyBindingImpl.load(LoadPropertyBindingImpl.java:58) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.bind.impl.PropertyBindingHandler.doLoadBinding(PropertyBindingHandler.java:140) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.bind.impl.PropertyBindingHandler.doLoad(PropertyBindingHandler.java:341) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.bind.impl.BinderImpl.loadComponentProperties0(BinderImpl.java:2491) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.bind.impl.BinderImpl.loadComponent0(BinderImpl.java:2458) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.bind.impl.BinderImpl.loadComponent(BinderImpl.java:2393) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.bind.tracker.impl.BindUiLifeCycle.reInitBinder0(BindUiLifeCycle.java:170) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.bind.tracker.impl.BindUiLifeCycle.reInitBinder(BindUiLifeCycle.java:109) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.bind.tracker.impl.BindUiLifeCycle.access$100(BindUiLifeCycle.java:55) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.bind.tracker.impl.BindUiLifeCycle$2.onEvent(BindUiLifeCycle.java:100) ~[zkbind_8.6.2.jar:8.6.2]
at org.zkoss.zk.ui.AbstractComponent.onEvent(AbstractComponent.java:3179) ~[zk_8.6.2.jar:8.6.2]
at org.zkoss.zk.ui.AbstractComponent.service(AbstractComponent.java:3127) ~[zk_8.6.2.jar:8.6.2]
at org.zkoss.zk.ui.AbstractComponent.service(AbstractComponent.java:3091) ~[zk_8.6.2.jar:8.6.2]
at org.zkoss.zk.ui.impl.EventProcessor.process(EventProcessor.java:138) ~[zk_8.6.2.jar:8.6.2]
at org.zkoss.zk.ui.impl.UiEngineImpl.processEvent(UiEngineImpl.java:1845) ~[zk_8.6.2.jar:8.6.2]
at org.zkoss.zk.ui.impl.UiEngineImpl.process(UiEngineImpl.java:1617) ~[zk_8.6.2.jar:8.6.2]
at org.zkoss.zk.ui.impl.UiEngineImpl.execUpdate(UiEngineImpl.java:1320) ~[zk_8.6.2.jar:8.6.2]
at org.zkoss.zk.au.http.DHtmlUpdateServlet.process(DHtmlUpdateServlet.java:611) ~[zk_8.6.2.jar:8.6.2]
at com.castortech.iris.ba.webviewer.internal.ZkUpdateServlet.process(ZkUpdateServlet.java:62) ~[com.castortech.iris.ba.webviewer/:na]
at org.zkoss.zk.au.http.DHtmlUpdateServlet.doGet(DHtmlUpdateServlet.java:487) ~[zk_8.6.2.jar:8.6.2]
at org.zkoss.zk.au.http.DHtmlUpdateServlet.doPost(DHtmlUpdateServlet.java:495) ~[zk_8.6.2.jar:8.6.2]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) ~[javax.servlet_3.1.0.v201410161800.jar:3.1.0]




CLR Error when using RunAndCollect rather than RunAndSave

When dynamically generated assemblies, we regularly get this exception:

Managed Debugging Assistant 'FatalExecutionEngineError' Message=Managed Debugging Assistant 'FatalExecutionEngineError' : 'The runtime has encountered a fatal error. The address of the error was at 0xa3851e22, on thread 0x25ac. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.'

which on loading the CLR symbols is always thrown with this call stack:

           ntdll.dll!NtWaitForSingleObject ()            Unknown
           KernelBase.dll!WaitForSingleObjectEx () Unknown
           ntdll.dll!RtlpCallVectoredHandlers()        Unknown
           ntdll.dll!RtlDispatchException() Unknown
           ntdll.dll!KiUserExceptionDispatch ()        Unknown
           kernel32.dll!BaseThreadInitThunk ()       Unknown
           ntdll.dll!RtlUserThreadStart ()    Unknown

This problem does not occur when AssemblyBuilderAccess is set to RunAndSave, but it reliably occurs when setting it to RunAndCollect. It always is thrown at this call stack. Is there a CLR bug with RunAndCollect? As far as we can tell, we hold references to the Assembly and Module reflection objects for these dynamic assemblies, which should mean they are not being collected ever. This should mean there is no difference in behaviour between RunAndSave and RunAndCollect.





Is there an event fired when a .NET collectable assembly is garbage collected (e.g. an Assembly emitted with RunAndCollect)

Is there an event fired when a .NET collectable assembly is garbage collected (e.g. an Assembly emitted with RunAndCollect). Something like AppDomain.AssemblyLoad Event?





C# Playing with generics, reflection and type inference

I'm doing some experiments with generic types and I'm struggling to achieve what I'm looking for. I'm actually not sure that it's even possible to do that. Here's a sample :

public class Request { }
public class RequestTest : Request { }

public class Response { }
public class ResponseTest : Response { }

public abstract class Base
{
    // some stuff
}

public abstract class WebMethodBase<TInput, TOutput> : Base
    where TInput : Request
    where TOutput : Response
{
    public abstract TOutput Execute();

    protected TInput Input { get; set; }
    protected TOutput Output { get; set; }

    public WebMethodBase(TInput input, TOutput output)
    {
        Input = input;
        Output = output;
    }
}

public class Test : WebMethodBase<RequestTest, ResponseTest>
{
    public override ResponseTest Execute()
    {
        // Do some treatment with the input
        Console.WriteLine("Test");
        return Output;
    }

    public Test(RequestTest input, ResponseTest output) : base(input, output) { }
}

public static class WebMethodBaseHelper
{
    public static WebMethodBase<TInput, TOutput> Create<TInput, TOutput>(TInput input, TOutput output)
        where TInput : Request
        where TOutput : Response    
    {
        Type baseType = typeof(WebMethodBase<TInput, TOutput>);
        Type childType = baseType.Assembly.GetTypes().Where((t) => baseType.IsAssignableFrom(t) && t.IsClass).FirstOrDefault();
        var constructor = childType.GetConstructor(new Type[] { typeof(TInput), typeof(TOutput) });
        return (WebMethodBase<TInput, TOutput>)constructor.Invoke(new Object[] {input, output});
}

class Program
{
    private static TOutput Execute<TInput, TOutput>(TInput input, TOutput output)
        where TInput : Request
        where TOutput : Response 
    {
        WebMethodBase<TInput, TOutput> webMethod = WebMethodBaseHelper.Create(input, output);
        return webMethod.Execute();
    }

    private static ResponseTest Run(RequestTest request)
    {
        return Execute(request, new ResponseTest());
    }

    static void main(string[] args)
    {
        ResponseTest result = Run(new RequestTest());
    }
}

This sample is working but it's unclear which implementation of WebMethodBase<> is instanciated. What I'd like to achieve is to modify the Execute function to be able to call it this way inside the Run function :

return Execute<Test>(request);

Since the Test class is inheriting WebMethodBase<> I guess somehow we should be able to retrieve the generic types and make the whole function generic as well, but I'm not really sure that this is something possible. I tried a lot of different ways already and this is the closest implementation I was able to get from what I want.

Any help or explanation of why this is not possible would be much appreciated.

Thanks





dimanche 26 janvier 2020

Java reflection - Get a class variable by passing the name

I have a class (it's a Singleton in my project) with some variables. I would like to get one of those variable by passing its name in a function. For now i have :

public final class Configuration {
   private static volatile Configuration instance = null;
   //Here usual code to instanciate singleton

   String var1;
   int var2;
   boolean var3;

   public static Object Get(String varname)throws IllegalArgumentException, IllegalAccessException {
       for(Field field : instance.getClass().getFields())
            if(field.getName() == varname) 
                return field.get(field);
       return null;
   }

}

From the debugger i know that instance.getClass().getFields() return an empty Field[], but i do not understand why.





overwriting value in complex object's instance with java reflection

I'm trying to write a method that changes one nested value of object. I think that java reflections are here the best way to do that but I'm having trouble developing the solution. What I'm trying to do is:

package abcClass;

import overwrite.ValueOverwriter;

public class main {
    public static void main(String[] args) {
        A obj1 = new A();
        B bClass = new B();
        C cClass = new C();
        cClass.setStringValue("XXX");
        bClass.setcClass(cClass);
        obj1.setbClass(bClass);

        E obj2 = new E();
        D dClass = new D();
        dClass.setSomeInt(10);
        obj2.setdClass(dClass);

        A newObj1 = (A) ValueOverwriter.overwiteValue(obj1, "bClass.cClass.someString", "YYY");
        E newObj2 = (E) ValueOverwriter.overwiteValue(obj2, "dClass.someInt", "20");
    }
}

Class with method that I'm trying to implement:

package overwrite;

import abcClass.Abcdef;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

public class ValueOverwriter {

    //        String path is path to value that is to be changed like: " aClass.bClass.cClass.stringValue"
    public static Abcdef overwiteValue(Abcdef obj, String path, String newValue) {
        List<String> propertyAddress = Arrays.asList(path.split("\\."));
        StringBuilder methodToInvokeName = new StringBuilder("obj");

        for (int i = 0; i < propertyAddress.size() - 1; i++) {
            methodToInvokeName.append("." + returnMethodName("get", propertyAddress.get(i)));
        }
        String setterMethodName = methodToInvokeName.toString() + "." + returnMethodName("set", propertyAddress.get(propertyAddress.size() - 1));
        String getterMethodName = methodToInvokeName.toString() + "." + returnMethodName("get", propertyAddress.get(propertyAddress.size() - 1));

        try {
            Method setterMethod = obj.getClass().getMethod(setterMethodName);
            setterMethod.invoke(obj, newValue);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return obj;
    }


    private static String returnMethodName(String method, String field) {
        return method + field.substring(0, 1)
                .toUpperCase() + field.substring(1);
    }
}

And some simple classes:

Abcdef interface:

    package abcClass;

    public interface Abcdef {
    }

A class:

    package abcClass;

    public class A implements Abcdef{
        private B bClass;

        public B getbClass() {
            return bClass;
        }

        public void setbClass(B bClass) {
            this.bClass = bClass;
        }
    }

B class:

package abcClass;

public class B{
    private C cClass;

    public C getcClass() {
        return cClass;
    }

    public void setcClass(C cClass) {
        this.cClass = cClass;
    }
}

C class:

package abcClass;

public class C{
    private String stringValue = "some String";

    public String getStringValue() {
        return stringValue;
    }

    public void setStringValue(String stringValue) {
        this.stringValue = stringValue;
    }
}

D class:

package abcClass;

public class D {
    private int someInt = 10;

    public int getSomeInt() {
        return someInt;
    }

    public void setSomeInt(int someInt) {
        this.someInt = someInt;
    }
}

E class:

package abcClass;

public class E implements Abcdef{
        private D dClass;

    public D getdClass() {
        return dClass;
    }

    public void setdClass(D bClass) {
        this.dClass = bClass;
    }
}

I need that this method would be able to handle different value types, maybe I should do interface with OverRider for such?

Now I'm getting Exception:

"C:\Program Files\Java\jdk1.8.0_191\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.3.2\lib\idea_rt.jar=64108:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.3.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_191\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_191\jre\lib\rt.jar;C:\Users\karolina.kosmala\batchWorkspace\spring-batch-master\field_overwrite\target\classes;C:\Users\karolina.kosmala\.m2\repository\org\springframework\spring-beans\5.2.3.RELEASE\spring-beans-5.2.3.RELEASE.jar;C:\Users\karolina.kosmala\.m2\repository\org\springframework\spring-core\5.2.3.RELEASE\spring-core-5.2.3.RELEASE.jar;C:\Users\karolina.kosmala\.m2\repository\org\springframework\spring-jcl\5.2.3.RELEASE\spring-jcl-5.2.3.RELEASE.jar" abcClass.main
java.lang.NoSuchMethodException: abcClass.A.obj.getBClass.getCClass.setSomeString()
    at java.lang.Class.getMethod(Class.java:1786)
    at overwrite.ValueOverwriter.overwiteValue(ValueOverwriter.java:25)
    at abcClass.main.main(main.java:19)
java.lang.NoSuchMethodException: abcClass.E.obj.getDClass.setSomeInt()
    at java.lang.Class.getMethod(Class.java:1786)
    at overwrite.ValueOverwriter.overwiteValue(ValueOverwriter.java:25)
    at abcClass.main.main(main.java:20)

Process finished with exit code 0




samedi 25 janvier 2020

How can I test whether a for loop is available in the Class?

Let me explain the use case first.

The use case is that a learner learning java is following a set of written instructions and using automated tests (read JUnit), I want to test whether they have successfully implemented the instruction.

Things that I need to find out programmatically, for example, is if a for loop exists in the code. Consider the following code

class AClass {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }
}

Is there a way that using reflection API, I can assert that AClass contains for(int i=1; i<11; i++)? Or any other way?

This question is an example. Ideally, there could be a code such as if (x) {} that I may want to find out inside a class.

I am not sure how feasible this is.

Thank you





Looking to call generic method where T implements multiple

I am trying to call the below generic method dynamically where T is associated to class and other interfaces as mentioned below. I am kind of stuck in problem on how to define those class and interfaces while calling generic method.

this is the generic method

 private async Task UpdateRevision<T>(Guid id) where T : class, IAEIMaster, IRevisionData
 {
      var dbSet = this._dbContext.Set<T>();

      var code = dbSet.SingleOrDefault(c => c.Id == id);
      int revision;
      ......
      ......
      code.Revision = revision;
      code.IsApproved = true;
 }

and this is where i am calling the above generic method

  var method = typeof(Mutation).GetMethod("UpdateRevision");
  var generic = method.MakeGenericMethod("what i need to put here"); // here i have got stuck in
  var task = (Task)generic.Invoke(this, new object[] { request.DataId });
  // also not sure how to define class, IAEIMaster, IRevisionData here

Could any one please let me know on this how to call that generic method that would be very grateful to me, many thanks in advance

I am using .Net core with EF core





vendredi 24 janvier 2020

JAVA. Using reflection for deep copy object

I try to copy an object by reflection. I haven't difficulties with copy primitive types, but i dont understand how copy reference types.

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
public class ReflMethod {
    private static final Set<Class<?>> WRAPPER_TYPES = getWrapperTypes();

    public Object CopyObject(Object object) throws ClassNotFoundException, IllegalAccessException, InstantiationException {

        Class clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Object instance =  object.getClass().newInstance();

        for(Field field : fields) {
            field.setAccessible(true);
            Class newClass = Class.forName(field.get(object).getClass().getName());
            if(isWrapperType(newClass)) {
                field.set(instance, field.get(object));
            }
            else if(!isWrapperType(newClass)) {

                //WEIRDNESS HERE
                field.set(instance, CopyObject(field.get(object).getClass().getName()));
                //WEIRDNESS HERE
            }
        }
        return instance;
    }

    public static boolean isWrapperType(Class<?> clazz)
    {
        return WRAPPER_TYPES.contains(clazz);
    }

    public static Set<Class<?>> getWrapperTypes()
    {
        Set<Class<?>> ret = new HashSet<Class<?>>();
        ret.add(Boolean.class);
        ret.add(Character.class);
        ret.add(Byte.class);
        ret.add(Short.class);
        ret.add(Integer.class);
        ret.add(Long.class);
        ret.add(Float.class);
        ret.add(Double.class);
        ret.add(Void.class);
        return ret;
    }
}

I want using recursion for copying reference types...Where do I think wrong?

public class Cat {
    private Phone phone;
    private int age;

    public Cat() {

    }

    public Cat(int age, Phone phone) {
        this.age = age;
        this.phone = phone;
    }

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Phone getPhone() {
        return phone;
    }
    public void setPhone(Phone phone) {
        this.phone = phone;
    }
}
public class Phone {
    private String name;
    public Phone() {

    }
    public Phone(String name) {
        this.name = name;
    }
    public void SetName(String name) {
        this.name = name;
    }
    public String GetName() {
        return name;
    }
}

And main class:

public class MainClass {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException {

        ReflMethod reflMethod = new ReflMethod();

        Phone phone1 = new Phone("IPhone");
        Cat cat1 = new Cat(20, phone1);
        Cat cat2 = (Cat)reflMethod.CopyObject(cat1);

        System.out.println("cat1 : " + cat1.getAge() + " " + cat1.getPhone().GetName());
        System.out.println("cat2 : " + cat2.getAge() + " " + cat2.getPhone().GetName());
        cat1.setAge(100);
        Phone phone = new Phone("Af");
        cat1.setPhone(phone);
        System.out.println("cat1 : " + cat1.getAge() + " " + cat1.getPhone().GetName());
        System.out.println("cat2 : " + cat2.getAge() + " " + cat2.getPhone().GetName());
    }
}

The code doesn't work because of the code marked as WEIRDNESS HERE.





Java java.lang.IllegalArgumentException: wrong number of arguments

I try access info(String var) method in a final class that has a non visible contstructor Class(String var0, Logger var1, LoggerContext var2)

try {
Constructor<? extends Logger> var0 = logger.getClass().getDeclaredConstructor(String.class, Logger.class, LoggerContext.class);

var0.setAccessible(true);

logger.getClass().getDeclaredMethod("info", String.class).invoke(var0.newInstance(), new String(message));

} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
}

and this is the error

java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)




jeudi 23 janvier 2020

PHP Reflection create class instance (object) with an array of arguments passed to the constructor

How to instantiate class Bar with PHP Reflection?

class code:

class Bar
{
    private $one;
    private $two;

    public function __construct($one, $two) 
    {
        $this->one = $one;
        $this->two = $two;
    }

    public function get()
    {
        return ($this->one + $this->two);
    }
}

I ran out of ideas, some of my guesswork is:

$class = 'Bar';
$constructorArgumentArr = [2,3];
$reflectionMethod = new \ReflectionMethod($class,'__construct');
$object = $reflectionMethod->invokeArgs($class, $constructorArgumentArr);

echo $object->get(); //should echo 5

but this will not work since invokeArgs() requires an object not a class name so I have a chicken-egg case: I don't have an object so I cannot use constructor method and I need to use constructor method to get the object.

I tried to pass null as $class as the first argument following the logic that constructor is called at the time when there's no object yet but I got: "ReflectionException: Trying to invoke non static method ..."

If there is no solution available by Reflection I'll accept any other (ie php function).

References:
Reflection Method
ReflectionMethod::invokeArgs





Scala Implementation of Reflection to find Member Name

If I have a case class situation like this:

case class ColorId(id: Int) 

With a companion object that looks like this:

/**
  * Contains all possible colors that can be applied.
  */
object ColorId {
  val RED = ColorId(1)
  val GREEN = ColorId(2)
  val BLUE = ColorId(3)
  val WHITE = ColorId(4)
  val BLACK = ColorId(5)
  val UNKNOWN = ColorId(6)
}

val blue = ColorId.BLUE

assert(blue.getNameString == "BLUE")

There is surely a way to use reflection to get the assert to be true. How should the implementation of the ColorId object's getNameString method look?

EDIT: There does not need to be a specific method. For example something like blue.getClass.getXXX.getName is acceptable.

EDIT #2: Removing this comparable part.





Difference between RTTI and Reflection in Java?

I was reading Thinking In Java and I noticed that the chapter on RTTI treats RTTI and Reflection separately. For me, both of these terms help to determine the type of an object at run time (hence, Runtime Type Information). I think maybe, I am missing something here because I read some people classify instanceof as RTTI and other things as Reflection.

Can someone elaborate on this a bit?

P.S. I am talking in terms of Java. I saw another question where the answer was based on C++ and it didn't make much sense in Java context





How to find all member of a class file by using ASM library or other similar library if more efficient?

I would like to create classpath scanner based on bytecode analisys, is there a way to find all members (Constructors, Methods, Fields) of a class file by using ASM library or other similar library if more efficient?





mercredi 22 janvier 2020

What is difference between java proxy & plain java class?

Proxy is used to intercept OR to surrogate OR change existing functionality of target object without modifying it, but same thing we can achieve using normal java class by inheriting target class & overriding it's methods.
Then what is exact usage of it ? How it is different & efficient from normal java class ?





How to use reflection in Scala. I am trying to use getDeclaredMethod()

How to use reflection in Scala. My code looks like below

click here for code screenshot

val arg = new Class[_](classOf[String], classOf[String], classOf[String])
val child = Class.forName("GenerateJSON").getClassLoader.getClass.getDeclaredMethod(function_name,arg).invoke(null,matcher1.group().replace("%",""),customfield,value)

This gives me an error - Error:(28, 21) class type required but Class[_] found var arg = new Class[_](classOf[String],classOf[String],classOf[String])





getClass.getFields returns fields from Scala Reflection library instead of fields from package

I am using the Scala reflection library to access and execute the main() function of a jar that I have attached to my project. I can do this much successfully, but now I would like to use Reflection to access a specific field in this jar and set its value at runtime.

However, when I run the code below, fields.map(f => print(f)) prints the fields of the Scala Reflection library, not the fields of the jar. Any idea why this is happening? I've been searching for a resolution for a week, and would greatly appreciate any help!

Code:

val rm = scala.reflect.runtime.currentMirror

val staticClass = rm.staticModule("com.dummy.package.name")

val im1 = rm.reflectModule(staticClass)

val x = im1.instance

val im = rm.reflect(x)

val fields = staticClass.getClass.getDeclaredFields

fields.map(f => print(f))

Output:

public final scala.reflect.internal.Symbols$Symbol scala.reflect.internal.Symbols$Symbol.scala$reflect$internal$Symbols$Symbol$$initOwner public final scala.reflect.internal.Names$Name scala.reflect.internal.Symbols$Symbol.scala$reflect$internal$Symbols$Symbol$$initName public final scala.reflect.internal.SymbolTable scala.reflect.internal.Symbols$SymbolContextApiImpl.$outer





C# - Exception thrown in property setter cannot be caught when called via reflection (SetValue())

my question is similar to Using reflection, setter throws exception which can't be caught, but the recommended solution does not solve my problem.

In the code below, I try to set the property of a class via two different ways: first, directly and second, via reflection. The setter throws an exception (in the real use case only if the given value is invalid) that should be caught at the place where the setter is called. But the exception is only caught in the first variant; in the second, the catch-block is never executed. What is the reason for this?

In my use case, I want to use the reflection variant but the program always terminates where the exception is thrown and I have no change to catch it.

The mentioned thread above recommends that either the Debugger is configured in such a way that it breaks at every exception (this cannot be the case as in the first variant, the exception is caught perfectly fine) or that the exception comes from somewhere else. Unfortunately, I do not know where it could come from otherwise.

Thank you very much for your help!

using System;
using System.Reflection;

namespace ReflectionTestConsole
{
    public class Program
    {
        public static void Main(string[] args)
        {

            Logic logic = new Logic();
            try
            {
                logic.MyProperty = 5;
            } 
            catch(Exception e)
            {   // in this case, the exception is caught here.
                Console.WriteLine("Exception was caught: " + e.Message);
            }

            try{
                PropertyInfo propInfo = logic.GetType().GetProperty("MyProperty");
                propInfo.SetValue(logic,5);
            }
            catch (Exception e)
            {   // in this case, the exception is not caught
                Console.WriteLine(e.Message);
            }

        }
    }

    public class Logic
    {
        private double variable;
        public double MyProperty
        {
            get
            {
                return variable;
            }
            set
            { //Check if value is valid and if not throw an exception
                throw new Exception("This is the exception");
            }
        }
    }
}




Method to populate a List

I'm in need to create a method which allows me to populate a List with the values of the constants that are defined in the own class.

To give you a quick example of the numerous (20 in total) constants that are defined in the class:

private const string NAME1 = "NAME1";
private const string NAME2 = "NAME2";
private const string NAME3 = "NAME3";
...

As you can see, the name of the constant equals the value of it, if that can help.

So far, looking at examples of different types of solutions that I've found in StackOverflow about similar problems, I've come up with this:

public static List<string> GetConstantNames()
{
   List<string> names = new List<string>();
   Type type = typeof(ClassName);

   foreach (PropertyInfo property in type.GetType().GetProperties())
   {
      names.Add(property.Name);
   }

   return names;
}

My experience as a programmer is quite low, same as my experience with C#; I'm not sure if type.GetType().GetProperties() references the constant names, same happens with the property.Name line.

Does this method do what I'm asking?





How does Hibernate fetch data in a OneToMany relationship under the hood?

I am developing an ORM library similar to Hibernate. Now I'm stuck with the OneToMany relationship. I'd like to know how to fetch automatically data from database when getter of the one side is called and how Hibernate does it under the hood.

Many side

public class Film {
    private int id;
    private String name;

    @JoinColumn(name="producer_id")
    private Producer producer;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Producer getProducer() {
        return producer;
    }

    public void setProducer(Producer producer) {
        this.producer = producer;
    }
}

One Side

public class Producer {
    @Id
    private int id;
    private String name;

    @OneToMany(mappedBy="producer")
    private Set<Film> films;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

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

    public void setName(String name) {
        this.name = name;
    }

    // When called, it executes: SELECT ... FROM Film where producer_id = ?
    public Set<Film> getFilms() {
        return films;
    }
}

In other words, I want to fill films inside Producer only when getFilms() is called.





How to work with varargs (number of arguments) and reflection in Kotlin

I've got this method (in java):

public void insert(final MyCustomObject... obj)

I know the package name and the class name of MyCustomObject as well as the method name so I am using it during reflection (using Kotlin):

val myCustomObjectClass = Class.forName("${packageName}${className}")
val myCustomObject = myCustomObjectClass.getConstructor(String::class.java, Long::class.java)
val insertMethod = classContainingInsertMethod.getDeclaredMethod("insert", myCustomObjectClass)

the class classContainingInsertMethod was created earlier. Now, how could I invoke the method? I got an exception that there is no such method. I am aware of that because it is a number of args, not a single one.

I tried using arrayOf(myCustomObjectClass)::class.java but this gave me just another exception. Using *myCustomObjectClass didn't work either.





mardi 21 janvier 2020

.NET reflection 3 times slower in .NET 4.7.x than in 3.5

I have an application that we upgraded form .NET 3.5 to .NET 4.7.2. The only problem really is performance from part of our code that uses reflection. Entire situation is best explained in a simple sample I uploaded to Gist: https://gist.github.com/vkocjancic/3e8a6b3496c412a75b1c85a1d2ba1111

Basically, we have a POCO class, which property methods throw exceptions, if value is not set for properties of non-nullable types.

A reflection is then used to get property names and values of instances of POCO class and popluate it to DataTable.

The sample and real life project source code is exactly the same. The only difference is that in one case it is compiled using .NET 3.5 and in second using .NET 4.7.2.

This is the average time elapsed in milliseconds for 10 invocations:

.NET 3.5    -> 231.1 ms
.NET 4.7.2  -> 713.5 ms

Can anyone elaborate why reflection is about 3 times slower in .NET 4.7.2 than in .NET 3.5 and how to fix that. The lag only happens, when properties are not set and throw exceptions. If you populate property values, there is no difference in performance.

If I run sample in debugger, .NET 3.5 build never triggers MissingFieldException. Build using .NET 4.7.2 triggers every exception.





Messing with String class fields with reflection in Android

Sometimes I like to mess with reflection just for the sake of it. Sorry if this is too broad. Could somebody explain to me what are the values I'm getting here in this code? This is running on Android.

private static void test() {
    try {
        String sVal = "Hello!";
        try {
            sVal.charAt(6);
        } catch (StringIndexOutOfBoundsException ex) {
            // This will happen
            ex.printStackTrace();
        }
        Field f = String.class.getDeclaredField("count");
        f.setAccessible(true);
        f.set(sVal, 10000);
        // Now, this won't fail
        sVal.charAt(6);
        byte[] buffer = sVal.getBytes();
        Log.v("Test", "buff.length = " + buffer.length); // buffer.length == 5465 ??
        String s = new String(buffer); // buffer now apparently contains random parts of memory
        Log.v("Test", "" + s);
    } catch (Throwable t) {
        t.printStackTrace();
    }
}




How to create a fast-call delegate that has parameters and return type of private types, speeding up DynamicInvoke

I'm struggling with creating a call to the private ImmutableDictionary.Add, which allows me to utilize the KeyCollisionBehavior for finer control (the Add method only throws when key and value are different, I need it to throw always).

I can get where I want to be with basic reflection, however, the overhead of calling Invoke on MethodInfo, or DynamicInvoke on the delegate is significant (in fact, it almost triples the time on each call, which is too significant in my scenario).

The signature of the functions I need to call:

/// call property Origin, this returns a private MutationInput<,>
private MutationInput<TKey, TValue> Origin {get; }

/// call ImmutableDictionary<,>.Add, this takes MutationInput<,> and returns private MutationResult<,>
private static MutationResult<TKey, TValue> Add(TKey key, TValue value, KeyCollisionBehavior<TKey, TValue> behavior, MutationInput<TKey, TValue> origin);

/// then call MutationResult<,>.Finalize
internal ImmutableDictionary<TKey, TValue> Finalize(ImmutableDictionary<TKey, TValue> priorMap);

The challenge here being that I need to pass a private type around, and that the private type is part of the signature.

Normally, after calling CreateDelegate, you can simply cast it to a Func<X, Y, Z> and this gives near-direct calling speed. But I don't know how to create a Func<,> if the generic types are private and/or not known at compile time. Using object doesn't work, gives a runtime exception on the cast.

Here's a shortened version (removed a lot of try/catch and checks) of the code I currently have. This works:

/// Copy of enum type from Github source of ImmutableDictionary
type KeyCollisionBehavior =
    /// Sets the value for the given key, even if that overwrites an existing value.
    | SetValue = 0
    /// Skips the mutating operation if a key conflict is detected.
    | Skip = 1
    /// Throw an exception if the key already exists with a different value.
    | ThrowIfValueDifferent = 2
    /// Throw an exception if the key already exists regardless of its value.
    | ThrowAlways = 3

/// Simple wrapper DU to add type safety
type MutationInputWrapper = 
    /// Wraps the type ImmutableDictionary<K, V>.MutationInput, required as 4th param in the internal Add#4 method
    | MutationInput of obj

/// Simple wrapper to add type-safety
type MutationResultWrapper =
    /// Wraps the type ImmutableDictionary<K, V>.MutationResult, which is the result of an internal Add#4 operation
    | MutationResult of obj

/// Type abbreviation
type BclImmDict<'Key, 'Value> = System.Collections.Immutable.ImmutableDictionary<'Key, 'Value>

/// Private extensions to ImmutableDictionary
type ImmutableDictionary<'Key, 'Value>() =
    static let dicType = typeof<System.Collections.Immutable.ImmutableDictionary<'Key, 'Value>>
    static let addMethod = dicType.GetMethod("Add", BindingFlags.NonPublic ||| BindingFlags.Static)
    static let addMethodDelegate = 
        let parameters = addMethod.GetParameters() |> Array.map (fun p -> p.ParameterType)
        let funType = 
            typedefof<Func<_, _, _, _, _>>.MakeGenericType [|
                parameters.[0]
                parameters.[1]
                parameters.[2]
                parameters.[3]
                addMethod.ReturnType
            |]
        Delegate.CreateDelegate(funType, addMethod) // here one would normally cast to Func<X, Y...>

    static let mutationResultFinalizeMethod = 
        if not(isNull addMethod) && not(isNull(addMethod.ReturnParameter)) then
            /// Nested private type MutationResult, for simplicity taken from the return-param type of ImmutableDictionary.Add#4
            let mutationResultType = addMethod.ReturnParameter.ParameterType
            if not(isNull mutationResultType) then
                mutationResultType.GetMethod("Finalize", BindingFlags.NonPublic ||| BindingFlags.Instance ||| BindingFlags.DeclaredOnly)
            else
                null
        else
            null

    /// System.Collections.Immutable.ImmutableDictionary.get_Origin  // of valuetype ImmutableDictionary<,>.MutationInput<,>
    static let getOrigin = dicType.GetProperty("Origin", BindingFlags.NonPublic ||| BindingFlags.Instance)

    /// Calls private member ImmutableDictionary<,>.Add(key, value, behavior, origin), through reflection
    static member private refl_Add(key: 'Key, value: 'Value, behavior: KeyCollisionBehavior, MutationInput origin) =
        // use Invoke or DynamicInvoke makes little difference.
        //addMethod.Invoke(null, [|key; value; behavior; origin|])
        addMethodDelegate.DynamicInvoke([|box key; box value; box <| int behavior; origin|])
        |> MutationResult

    /// Gets the "origin" of an ImmutableDictionary, by calling the private property get_Origin
    static member private refl_GetOrigin(this: BclImmDict<'Key, 'Value>) =
        getOrigin.GetValue this
        |> MutationInput

    /// Finalizes the result by taking the (internal) MutationResult and returning a new non-mutational dictionary
    static member private refl_Finalize(MutationResult mutationResult, map: BclImmDict<'Key, 'Value>) =
        mutationResultFinalizeMethod.Invoke(mutationResult, [|map|])
        :?> BclImmDict<'Key, 'Value>

    /// Actual Add, with added control through CollisionBehavior
    static member InternalAddAndFinalize(key: 'Key, value: 'Value, behavior, thisMap) =
        let origin = ImmutableDictionary.refl_GetOrigin(thisMap)
        let mutationResult = ImmutableDictionary.refl_Add(key, value, behavior, origin)
        let finalizedMap = ImmutableDictionary.refl_Finalize(mutationResult, thisMap)
        finalizedMap

I realize the code above is in F#, but if you know how to fix this in C# I've no problem with translating your answer into my preferred target language.





java.lang.ClassCastException: [Z cannot be cast to [Ljava.lang.String in reflective toString on model class

I have a model class in java and I overwrote the toString to provide me with a custom toString. The toString uses reflection to find the field names and values and it works when I run it locally via my ide. However when I run it via mvn agents I always seem to get the error:

java.lang.ClassCastException: [Z cannot be cast to [Ljava.lang.String

Here is the toString:

@SneakyThrows
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Class<?> thisClass = Class.forName(this.getClass().getName());
        Field[] aClassFields = thisClass.getDeclaredFields();
        for (Field f : aClassFields) {
            String fName = f.getName();
            fName = fName.startsWith("_") ? fName.substring(1) : fName;
            if (null != f.get(this)) {
                if (f.get(this) instanceof String || f.get(this) instanceof List) {
                    sb.append(getVariableNameStr(fName, f.get(this).toString()));
                } else {
                    StringBuilder stringArrayStr = new StringBuilder();
                    for (String s : (String[]) f.get(this)) {
                        stringArrayStr.append(fName).append(": ").append(s).append(", ");
                    }
                    sb.append(stringArrayStr);
                }
            }
        }
        return sb.toString().substring(0, sb.toString().length() - 2);
    }

The line it fails on in the code is the following:

for (String s : (String[]) f.get(this)) {

Why does this pass locally and fail using mvn? Can anybody tell me what is incorrect about this line?

Just to clear up - the model class has 3 types of field - String, List and String array. The errored line occurs on String array entries.

A





lundi 20 janvier 2020

How to get a list of a struct's methods in Go?

I have a library in which there are both Client and MockClient structs which both implement the same ClientInterface interface. I would like to write unit tests to keep these structs in sync so that they not only just implement the interface, but so that MockClient has all of Client's methods. To this end, I would like to get a list of a struct's methods in order to print an informative error message if one of the methods of Client is missing from MockClient.

I've tried adapting How to get the name of a function in Go? to this simplified example:

package main

import (
    "fmt"
    "reflect"
    "runtime"
)

type Person struct {
    Name string
}

func (person *Person) GetName() string {
    return person.Name
}

func main() {
    person := Person{Name: "John Doe"}
    personValue := reflect.ValueOf(&person)

    for i := 0; i < personValue.NumMethod(); i++ {
        fmt.Println(runtime.FuncForPC(personValue.Method(i).Pointer()).Name())
    }
}

What I would like is for this script (shared at https://play.golang.org/p/HwvhEPfWI5I) to print GetName. However, instead, it prints

reflect.methodValueCall

How can I get this script to print the names of *Person's methods?





How do I get the source for a Python class I declared programmatically?

I'm trying to use inspect.getsource() to get the source of a class that was defined like this:

import inspect

Cat = type('Cat', (), {})

def meow_local(self):
  print("meow")

Cat.meow = meow_local

print(inspect.getsource(Cat))

The error I get from inspect is:

OSError: could not find class definition

It is understandable that inspect does not know the correct place to find the Cat class. Where should I tell inspect to look?

Or is there another way to get the same results?





How to Pass Type dynamically to System.Data.Entity.Database.SqlQuery

I would like to create a procedure that returns everything dynamically so that I don't have to develop a switch on string to find the correct type. I tried to get a type from a string:

Type myDynamicType = Type.GetType("myDynamicType");
var objects = dataContext.Database.SqlQuery<myDynamicType>($"SELECT * FROM MY_TABLE WHERE Id > 0").ToList();

This code doesn't work because return this error:

Error CS0118 'myDynamicType' is a variable but is used like a type





dimanche 19 janvier 2020

In Go, how to check that an interface implements all of a struct's exported methods?

I'm working on a Go library in which I've used the interfacer tool (https://github.com/rjeczalik/interfaces) to create an interface from a struct, and subsequently ran moq (https://github.com/matryer/moq) to generate a mock object for that interface. Now I would like to write a unit test that fails if someone adds an exported method to the struct without updating the interface and the mocks.

At a high level, it seems to me that I could get the reflect.Value of both the interface and the struct and call NumMethod() on each and then check that the numbers are equal. I'm struggling to implement this idea, however.

For example, if I try this:

package main

import (
    "fmt"
    "reflect"
)

type PersonInterface interface {
    GetName() string
}

type Person struct {
    Name string
}

func (person *Person) GetName() string {
    return person.Name
}

func main() {
    person := Person{}
    v := reflect.ValueOf(&person)
    fmt.Println(v.NumMethod())

    var personInterface PersonInterface
    w := reflect.ValueOf(personInterface)
    fmt.Println(w.NumMethod())
}

I'm able to call get the number of methods of the person, but not of the personInterface, as this panics with the error message

reflect: call of reflect.Value.NumMethod on zero Value

Here is the full error:

> go run assert_struct.go
1
panic: reflect: call of reflect.Value.NumMethod on zero Value

goroutine 1 [running]:
reflect.Value.NumMethod(0x0, 0x0, 0x0, 0x1)
    /usr/local/Cellar/go@1.12/1.12.12/libexec/src/reflect/value.go:1262 +0xc1
main.main()
    /Users/kurt/Documents/Scratch/assert_struct.go:27 +0x1a5
exit status 2

How could I get the number of methods implemented by an interface, and more generally, how would I go about checking that an interface implements all exported methods of a struct?





How to access variable from *.class file with reflection or any other way [duplicate]

Suppose container.class contain

private static int height variable.

How to access this variable with reflection.

I can't get a way to access this variable.





How I can update struct's array field value via reflect in Go?

I want to edit struct fields' value as interface{} parameters. I done almost, but when struct has array field, I couldn't modify that. I tried to find proper function with array value, but I couldn't find that. Here is my code.

edit_struct_via _interface.go

package main

import (
    "reflect"
    "fmt"
)


type myStruct struct {
    Name    [8]byte
    TID     [4]byte
    Chksum  uint16
}

func main() {
    var s = new(myStruct)
    name := []byte("Mike")
    tid  := []byte{0x01, 0x02, 0x03, 0x05}
    setArrayField(name, s.Name[:])
    setArrayField(tid, s.TID[:])
    s.Chksum = 0x0101

    myObj := reflect.ValueOf(s).Elem()

    typeOfMyObj := myObj.Type()
    for i := 0; i < myObj.NumField(); i++ {
        f := myObj.Field(i)
        fmt.Printf("%d: %s %s = %v\n", i,
            typeOfMyObj.Field(i).Name, f.Type(), f.Interface())
    }

    newName := []byte("Emil")
    myObj.Field(0).SetBytes(newName[:])
    // I trying to change array field at here, but panic occur here.
    // Because SetBytes must been called on slice, but myObj.Field(0) is array.

    myObj.Field(2).SetUint(99)             // It works.
    fmt.Println("s is now: ", *s)
}

func setArrayField(src []byte, target []byte) {
    // retun if src is bigger than target
    if len(src) > len(target){
        return
    }

    for index, item := range src {
        target[index] = item
    }
}

When I run above code, I get

0: Name [8]uint8 = [77 105 107 101 0 0 0 0]
1: TID [4]uint8 = [1 2 3 5]
2: Chksum uint16 = 257
panic: reflect: call of reflect.Value.SetBytes on array Value

goroutine 1 [running]:
reflect.flag.mustBe(...)
        /usr/local/go/src/reflect/value.go:208
reflect.Value.SetBytes(0x4a6180, 0xc000098010, 0x191, 0xc000098078, 0x4, 0x4)
        /usr/local/go/src/reflect/value.go:1557 +0x140
main.main()
        /home/hornet/go/src/gateway-golang/edit_struct_via _interface.go:33 +0x522
exit status 2

I'm using Ubuntu 18.04 and go1.13 linux/amd64





Is it good idea to replace reflection calls with static Dictionaries in the whole application?

I have designed and implemented an enterprise application development framework in which I have used Reflection in different layers (especially in the UI layer where I have created several generic User controls that use reflection almost on any HttpRequest that users make.) a lot!

When I compare forms that do not use reflection at all to the ones that do, it is obvious to me that Reflection has become a performance bottleneck.

After doing some research and reviewing answers such as caching reflected properties and their custom attributes in c#

I have came up with the idea to create a utility ReflectionService which will perform the reflection for the first time it is required and then store it in a static Dictionary. In this way further reflection calls by any users will retrieve the result from the static dictionaries.So the static dictionaries are acting as some kind of application state here.

From a Design and Performance perspective, will it be a good idea to create such a service (ReflectionService) and move all the required reflection calls into this service?





samedi 18 janvier 2020

implement a generic argument method in GO

I have a code in GO, which includes many execution methods. Each method receives it own struct of parameters. I want a dispatcher to call each method with its related struct.

The dispatcher receives the name of the execution method, and a JSON of the parameters struct. Then, it uses reflection to build the struct, and calls the method.

The problem is I get compilation error unless I create the execution methods using empty interface. In the example below I have 2 execution methods: api1 is compiling, but is using the empty interface and explicit casting. api2 is what I want to do, but it is failing with compile error:

cannot use api2 (type func(Api2Parameters)) as type Api in assignment

How can I make api2 usage compile?

import (
    "encoding/json"
    "log"
    "reflect"
)

type Api func(arguments interface{})

type ApiDetails struct {
    Executor       *Api
    ParametersType reflect.Type
}

var Apis map[string]*ApiDetails

func RunApi(apiName string, data string) {
    api := Apis[apiName]
    parameters := reflect.New(api.ParametersType).Interface().(interface{})
    _ = json.Unmarshal([]byte(data), parameters)
    (*api.Executor)(parameters)
}

type Api1Parameters struct {
    Count1 int
    Id1    string
}

func api1(arguments interface{}) {
    parameters, _ := arguments.(*Api1Parameters)
    log.Printf("api1 parameters(%+v)", parameters)
}

type Api2Parameters struct {
    Count2 int
    Id2    string
}

func api2(arguments Api2Parameters) {
    log.Printf("api2 parameters(%+v)", arguments)
}

func Test() {
    // this assignment works fine
    var api_1 Api = api1
    Apis["api1"] = &ApiDetails{
        Executor:       &api_1,
        ParametersType: reflect.TypeOf(Api1Parameters{}),
    }

    // this assignment produce compile error
    var api_2 Api = api2
    Apis["api2"] = &ApiDetails{
        Executor:       &api_2,
        ParametersType: reflect.TypeOf(Api2Parameters{}),
    }

    RunApi("api1", `{"Count1":19, "Id1":"a"}`)
    RunApi("api2", `{"Count2":34, "Id2":"b"}`)
}




Checking if the return of a method is List

I'm trying to get the return type of a method using reflection, however I don't seem to be able to check for List<String> specifically.
I did it in a very hacky way:

if (method.getGenericReturnType().getTypeName().equalsIgnoreCase("java.util.List<java.lang.String>"))

Which isn't really what I should be doing, so I was wondering if there is a better solution.





Is it possible to beat Reflection by caching Types?

So I'm working with a lot generic types and using reflection to invoke their various methods. I've noticed that invoking a method via

//Subject is the generic type
Subject.GetType().GetMethod("methodName").Invoke(Subject, args);

seems to work okay and at the same time is dreadfully slower than invoking the methods on the object directly. I understand that I'm trading performance for flexibility and that nothing will ever be as fast the direct approach but I'd like to try and do better.

To this end I though it might be better if I cached the information ahead of time. Perhaps created a bit of front end load on application start up but hopefully reducing the overhead of the calls from there on.

    public class TypeCache : IDictionary<Accessor, Dictionary<string, MethodInfo>>
    {
        public Dictionary<Accessor, Dictionary<string, MethodInfo>> Cache { get; set; }

        public TypeCache(Type type)
        {
            Cache = new Dictionary<Accessor, Dictionary<string, MethodInfo>>();

            Cache.Add(Accessor.Method, new Dictionary<string, MethodInfo>());
            Cache.Add(Accessor.Get, new Dictionary<string, MethodInfo>());
            Cache.Add(Accessor.Set, new Dictionary<string, MethodInfo>());

            foreach (var method in type.GetMethods())
            {
                Cache[Accessor.Method].Add(method.Name, method);
            }

            var properties = type.GetProperties();

            foreach (var property in properties)
            {
                var getter = property.GetMethod;
                var setter = property.SetMethod;

                Cache[Accessor.Get].Add(getter.Name, getter);
                Cache[Accessor.Set].Add(setter.setter);
            }
        }

This allows me to replace the reflective call from above with the dictionary call below:

TypeCache[Accessor.Method][binder.Name].Invoke(InnerSubject, args);

Now making the caches singletons and other such efforts aside I'm still coming up a bit short on the performance gains here.

I've noticed that I'm about 15% on average worse than reflection. Is there any way to speed this up? I thought by using a dictionary based approach we might see some improvement. Perhaps if I accessed the three directories (Getters, Setters, and Public Methods) directly instead of flipping through an additional dictionary? To reduce the level of chained calls? Or find some way to assign them all to a single dictionary that gets accessed directory? Would this be worth pursuing?

I attempted to look at libraries like FastMember and I tried my hand at some IL, FastMember only offers access to properties in so far as I've found and IL looks like it would be a study in its own just to get this done.





Dynamically call function not bound to a struct in Golang [duplicate]

I'm trying to call functions that are not bound to any form of struct using reflection which doesn't seem to be possible.

I keep running into the issue of having to call reflect.ValueOf(T) which isn't possible since the functions are not bound to any form of struct.

// main.go

const subPackage = "subPackage"

func main() {
    set := token.NewFileSet()
    packs, err := parser.ParseDir(set, subPackage, nil, 0)

    if err != nil {
        fmt.Println("failed to parse package:", err)
        os.Exit(1)
    }

    var funcs []*ast.FuncDecl

    for _, pack := range packs {
        for _, f := range pack.Files {
            for _, d := range f.Decls {
                if fn, isFn := d.(*ast.FuncDecl); isFn {
                    funcs = append(funcs, fn)
                    reflect.ValueOf(T)MethodByName(fn.Name.Name) // not possible since T would need to be a struct!
                }
            }
        }
    }
}

// subPackage/test.go

func testFunc() {
    fmt.Println("hello world")
}

The code currently just parses the directory subPackage and gets all the root-level function declarations, I'm just not sure how to go about calling the unbound functions without a struct.





Find a class field's comes from another calsses

public class MyClassA
{
    public int Test;
    public List<MyClassB> StrTest; 
    void MyClassA()
    {
        StrTest = new List<MyClassB>();
        StrTest.Add(new MyClassB());
    }
}
public class MyClassB
{
    public int value;
}
private string ToStr()
{
    // By Reflection 
}
void main()
{
   MyClassA A = new MyClassA();
   string str = ToStr(A.StrTest[0].value);
   Console.WriteLine(str);
}

The output is "A.StrTest[0].value".

The main question is how can find a class field's comes from another classes





vendredi 17 janvier 2020

Storing object instance method with given attribute to be called later

As the title says, using reflection I get methods of the type that have a given attribute. I then want to store that method of that instance of the object so I can call it at a later time. I'm not sure how to store that method with that instance in a dictionary that holds Action. The message is the key use in the dictionary. All the methods that have this attribute will be required to take 1 argument of dynamic type.

static Dictionary<string, Action<dynamic>> networkHooks = new Dictionary<string, Action<dynamic>>();

private static void RegisterNetworkMethods(Type type, INetworkEnabled obj)
{
    // get the methods of this type that have the NetworkMethodAttribute
    var methods = (from m in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
                       where m.GetCustomAttributes(false).OfType<NetworkMethodAttribute>().Count() > 0
                       select m).ToList();

    foreach(var method in methods)
    {
        // get the NetworkMethodAttribute Message variable that was assigned
        var message = method.GetCustomAttribute<NetworkMethodAttribute>().Message;

        // todo: store this instance method in an Action somehow so it can be called later
        // networkHooks.Add(message, ???);
    }
}




Is it possible to delegate methods implementations

Given a function which creates lambdas. Is it possible to delegate the implementation of a declared function to a returned lambda (analogue to by-delegated properties). If by would exist for functions it could look like this:

private fun printFunCreator(): () -> Unit { return { println("Hello world")} }
fun printHelloWorld() by printFunCreator()

What I am not looking for:

I do not want to create an extra property of the lambda to delegate the call like this:

private fun printFunCreator(): () -> Unit { return { println("Hello world")} }
private val printFun = printFunCreator()
fun printHelloWorld() = printFun.invoke()

And I do not want to create a new lambda instance for each execution like this:

private fun printFunCreator(): () -> Unit { return { println("Hello world")} }
fun printHelloWorld() = printFunCreator().invoke()




Get Properties From Dynamic Deserialized Json Object with Reflection - .NET Core 3.1 C#

I am currently learning how to do reflection and I have been succesful with regards to getting the propeties and values of a stringly typed class. However, when I try with a dynamic object, I get an exception:

System.Reflection.TargetParameterCountException: Parameter count mismatch.

I've tried some of the solutions (e.g. object foo = dynamic obj then using obj) here but none seem to work because they don't quite reflect my problem.

Here is my code:

dynamic evtPc1 = JsonConvert.DeserializeObject(json);

PropertyInfo[] properties = evtPc1.GetType().GetProperties();

for (int i = 0; i < properties.Length; i++)
{
    Console.WriteLine($"Property: {properties[i].GetValue(evtPc1)}");
}




Dynamic create JTable in runtime

i'm trying create jtable use users pojo class. User create pojo class, i load him in runtime and create jtable. Say me,please, how i can do doing that?

String loadedClass = array.getJSONObject( 0 ).getString( "value" );
Class customFilterClass = new LoaderDynClass( getContext(), pack ).loadClass( loadedClass, true );

customFilterClass - users class type

StringReader reader = new StringReader( filterList );
//customFilterClass extent FilterTableModel. FilterTableModel parent abstract class
List<FilterTableModel> filterTableModelList = objectMapper.readValue( reader, new TypeReference<List<FilterTableModel>>(){} );

i can doing that with reflection API, but i'm don't know how receive List list. And how indicate type for my List

So sorry my english))





In C# is it possible to check if the method is an iterator via reflection?

The question is rather straightforward. Given a MethodBase or a MethodInfo instance how can I check if it represents an iterator method (with yield statements) or a common method (without yield statements)?

I have noticed a IteratorStateMachineAttribute in CustomAttributes property but here it is mentioned that one should not rely on this attribute.





jeudi 16 janvier 2020

How to get child classes with prefix packages using reflection classloading from deployment folder in Java?

Tried below code but it's giving zero results (subTypesOf size is zero).

 File projectFolder = new File("project_folder_some_path");
 final Set<URL> urls = new HashSet<>();
        Files.walkFileTree(projectFolder.toPath(), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toString().endsWith(".class")) {
                    urls.add(file.toFile().toURI().toURL());
                }
                return super.visitFile(file, attrs);
            }
        });

        URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[0]), getClass().getClassLoader());
        ConfigurationBuilder configuration = new ConfigurationBuilder()
                .addClassLoader(classLoader)
                .addUrls(urls)
                .setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner())
                .filterInputsBy(new FilterBuilder().includePackage("com.comp"));
        Reflections reflections = new Reflections(configuration);
        Set<Class<?>> subTypesOf = (Set<Class<?>>) reflections.getSubTypesOf(classLoader.loadClass("com.comp.framework.bean.SuperNumeratorIdEntity"));
// subTypesOf  size is zero
        classLoader.close();

here subTypesOf size is zero. But the class files are present in project folder which extends com.comp.framework.bean.SuperNumeratorIdEntity

The class i am looking for looks like this: public class XyzEntity extends SuperNumeratorIdEntity





Memory Violation Dynamically Appending to Methods at runtime

Disclaimer: I'm doing this for learning purposes. This is not going to be used in code.

I'm researching dynamically appending to methods at runtime. I found a very useful stack overflow question reference for getting me started.

I have a simple controller which I'm using as a test to verify my methods are swapping:

public class ValuesController : ControllerBase
{
    static ValuesController() {
        var methodToReplace = typeof(ValuesController).GetMethod(nameof(ValuesController.Seven),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        var methodToAppend = typeof(ValuesController).GetMethod(nameof(ValuesController.Eight),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        new Initializer(methodToReplace, methodToAppend);
    }

    [HttpGet("Seven")]
    public int Seven(string id)
    {
        return 7;
    }

    [HttpGet("Eight")]
    public int Eight(string id)
    {
        return 8;
    }
}

I have a class Initializer which is in charge of handling appending to the method.

public class Initializer
{
    public Initializer(MethodInfo methodToReplace, MethodInfo methodToAppend)
    {
        var dummyMethod = typeof(Initializer).GetMethod(nameof(Dummy),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        var proxyMethod = typeof(Initializer).GetMethod(nameof(Proxy),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        var appendedMethod = typeof(Initializer).GetMethod(nameof(Appended),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        dummyMethod.OneWayReplace(methodToReplace);
        methodToReplace.OneWayReplace(proxyMethod);
        appendedMethod.OneWayReplace(methodToAppend);
    }

    public int Proxy(string id)
    {
        Dummy(id);
        return Appended(id);
    }

    public int Dummy(string id)
    {
        return 0;
    }

    public int Appended(string id)
    {
        return 0;
    }
}

And then I have the Extensions which I've obtained from the original stackoverflow question:

public static class InjectionExtensions
{
    // Note: This method replaces methodToReplace with methodToInject
    // Note: methodToInject will still remain pointing to the same location
    public static unsafe MethodReplacementState OneWayReplace(this MethodInfo methodToReplace, MethodInfo methodToInject)
    {
        //#if DEBUG
        RuntimeHelpers.PrepareMethod(methodToReplace.MethodHandle);
        RuntimeHelpers.PrepareMethod(methodToInject.MethodHandle);
        //#endif
        MethodReplacementState state;

        IntPtr tar = methodToReplace.MethodHandle.Value;
        var inj = methodToInject.MethodHandle.Value + 8;

        if (!methodToReplace.IsVirtual)
            tar += 8;
        else
        {
            var index = (int)(((*(long*)tar) >> 32) & 0xFF);
            var classStart = *(IntPtr*)(methodToReplace.DeclaringType.TypeHandle.Value + (IntPtr.Size == 4 ? 40 : 64));
            tar = classStart + IntPtr.Size * index;
        }
#if DEBUG
        tar = *(IntPtr*)tar + 1;
        inj = *(IntPtr*)inj + 1;
        state.Location = tar;
        state.OriginalValue = new IntPtr(*(int*)tar);

        *(int*)tar = *(int*)inj + (int)(long)inj - (int)(long)tar;
        return state;

#else
        state.Location = tar;
        state.OriginalValue = *(IntPtr*)tar;
        * (IntPtr*)tar = *(IntPtr*)inj;
        return state;
#endif
    }
}

Note: Using the current setup everything works fine. However, the second I change the Initializer class to be a generic class Initializer<T> I get a memory violation:

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

My guess is that either the methodToReplace.DeclaringType.TypeHandle.Value calculation differs for generics, Or since the compiler is the one who generates the generic class it written to protected memory?

How can I append to methods that reside in generic classes?