mardi 2 juin 2020

Get default property value from type, without instancing a class

Here is sample code

public class Foo
{
    public string Data { get; set; } = "Example";
}

how can I get the default value "Example" of property Data from typeof(Foo)? we don't instance the class, don't change class.

I tried to find a solution from this post: C# Get property value without creating instance? but no luck.

Thanks.





How can I know both class are from same Generic class

Here is sample code. How can I know both Foo and Bar are from same class Base<>?

class Program
{
    static void Main(string[] args)
    {
        var foo = typeof(Foo).IsAssignableFrom(typeof(Base<,>));
        var bar = typeof(Bar).IsAssignableFrom(typeof(Base<,>));
    }
}

public abstract class Base<TInput, TOutput>
{
    public abstract TOutput Run(TInput input);
}


public class Foo : Base<int, string>
{
    public override string Run(int input)
    {
        return input.ToString();
    }
}

public class Bar : Base<string, string>
{
    public override string Run(string input)
    {
        return input.Replace(".", "").ToString();
    }
}

enter image description here





Why can't I get the MouseDown event of a Control via Reflection

I try to remove a EventHandler with .NET Reflection. When I use my own testclass (changed the argument from Control that to TestClass that), it works.

But when I want to do it with a WindowsForms Control, I can't get the public field of the event (strictly speaking I dont get any public instance field). What differs between my TestClass and a WindowsForms Control. The "MouseDown" event and the event in my TestClass are both public.

        static void  RemoveHandler( Control that )
        {
            //adding an eventhandler for testing
            that.MouseDown += (obj,arg) => { };

            string eventName = "MouseDown";
            //this works, but I need the Field, to get the Invocationlist
            var testEventInfo = that.GetType().GetEvent( eventName, BindingFlags.Public | BindingFlags.Instance );

            if ( testEventInfo != null )
            {
                //this fails, Declaring Type of my Event "MouseDown" is Control  testEventFieldInfo stays null
                var testEventFieldInfo = testEventInfo.DeclaringType.GetField( testEventInfo.Name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField );

                //trying to get all public events fails too, fields is always empty
                // var fields = testEventInfo.DeclaringType.GetFields( BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField );
                if ( testEventFieldInfo != null )
                {
                    var testEventFieldValue = (System.Delegate)testEventFieldInfo.GetValue( that );
                    if ( testEventFieldValue != null ) // if its null no Delegates are hooked
                    {
                        var invocationList = testEventFieldValue.GetInvocationList();
                        //var removeMethod = testEventInfo.GetRemoveMethod();

                        foreach ( var eventHandlerDelegate in invocationList )
                        {

                            testEventInfo.RemoveEventHandler( that, eventHandlerDelegate );
                        }
                    }
                }
            }
        }

What I tried is dealing with inheritance. (TestClass is a drived Class, and the base Class declares the event) Found out that .GetEvent gets also Event from all base classes, but GetField does not, so I added the access to the .DeclaringType of the Field. All this works with my TestClass, but not with a Control-derrived type (i.e. Button or ListBox)

What I found out too is, that there is a field "EventMouseDown", which is NonPublic and Static. But I cant find any Documentation on this. And the Name I hooked on is "MouseDown"

So maybe you know, where is my lack of knowledge. Thank you very much.





Is using method reference bad for performance?

I need to build my own library to handle events coming from an event bus, the first solution I came up with was an abstract class made like this one:

public abstract class MyEventListener<T> extends RealEventListener{
      private final Class<T> type; //the event class type
      private final String stream; //the stream 

      public abstract onEvent(T type); //the method my subclasses have to implement

      @Overrides
      public void onEvent(byte[] evt){ //takes the original, clunky method and evolves it with typing
          //convert and do stuff
          onEvent(convertedEvent); //call method
      }      
}

so, the classes only do:

@Component
public class Child extends MyEventListener<AType>{
    public Child(){
        super(AType.class, "stream"); //registers
     }

    @Overrides
    public void onMessage(AType evt){ //do stuff
}

I find this approach somewhat limiting and outdated (at least seeing the latest libraries). An example I can think of is that, this way, you are forced to handle separate events in separate classes.

So, I though of using annotations to have something like this:

@EventListener("stream") //1. you define the stream in this custom class annotation
public class Child {  //so no need to extend

   @ListenTo(type=AType.class) //2. you define the type on methods, this way a single class can handle more
   public void onMessage(AType event, //any other param){

   }

Now, for the magic behind, I though about using a startup annotation processing to retrieve the methods:

public void initialize(@EventListener List<Object> listeners) { //I inject all objects
    listeners.stream().map(..).collect(..) //use reflection to get all methods annotated with @ListenTo and put them inside of map <String, Method>

    eventBus.registerListener(new MyEventListener(methodMap)); //
}

Now, the listener will take somewhat the type from the original byte event and call the method:

String className = getClassFromEvent(evt);
listenerMap.get(className).invoke(evt);

According to you is this approach valid and, most importantly, efficient? Or, excluding the initialization phase, it could lead to performance problems at runtime? Of course I should make static checks at initialization to make sure that the annotated methods declare the event as parameter but it seems cleaner to me than the first one.





lundi 1 juin 2020

What am i doing wrong with this IL generation

I started to dive into System.Reflection.Emit and am trying to generate the IL of a constructor and execute some code in the body.

I want to generate the IL for the following piece of code:

public SomeConstructor()
{
   var prop = typeof(string).GetField(NavigationProxy", BindingFlags.Instance | BindingFlags.Public);
   prop.SetValue(this, new NavigationProxy(this));
}

So far I have the following:

var emitter = ctor.GetILGenerator();
emitter.Emit(OpCodes.Nop);

emitter.Emit(OpCodes.Ldarg_0);
for (var i = 1; i <= parameters.Length; ++i)
{
   emitter.Emit(OpCodes.Ldarg, i);
}
emitter.Emit(OpCodes.Call, constructor);
emitter.Emit(OpCodes.Nop);

emitter.Emit(OpCodes.Nop);
emitter.Emit(OpCodes.Ldtoken, typeof(Application));
emitter.Emit(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle), new Type[1] { typeof(RuntimeTypeHandle) }));
emitter.Emit(OpCodes.Ldstr, nameof(Application.NavigationProxy));
emitter.Emit(OpCodes.Ldc_I4_S, 20);
emitter.Emit(OpCodes.Callvirt, typeof(Type).GetMethod(nameof(Type.GetField), new Type[2] { typeof(string), typeof(BindingFlags) }));
emitter.Emit(OpCodes.Stloc_0);
emitter.Emit(OpCodes.Ldloc_0);
emitter.Emit(OpCodes.Ldarg_0);
emitter.Emit(OpCodes.Ldarg_0);
emitter.Emit(OpCodes.Newobj, typeof(XamarinNavigationProxy).GetConstructor(new Type[1] { typeof(Application) }));
emitter.Emit(OpCodes.Callvirt, typeof(FieldInfo).GetMethod(nameof(FieldInfo.SetValue), new Type[2] { typeof(object), typeof(object) }));
emitter.Emit(OpCodes.Nop);
emitter.Emit(OpCodes.Ret);

However when generating an instance of my new type using

Activator.CreateInstance(myType);

I get the following error:

System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
Inner Exception
InvalidProgramException: Common Language Runtime detected an invalid program

I've tried decompiling the code in LINQPad and have copied the IL directly and still no luck, anyone got any ideas?





is there any way load FXML in package except deafult package in java [duplicate]

i am trying to load FXML loader in a specific package but i get java.lang.reflect.InvocationTargetException and java.lang.IllegalStateException: Location is not set. i dont know what to do i dont want to put my classes in default package due to some reason what should i do

here is my code and note the class main is in view package

private static Parent loadFXML(String fxml) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getClassLoader().getParent().getResource("view." + fxml + ".fxml"));
        return fxmlLoader.load();
    }





Can we create another javafx project from our project?

i have a javaFX project entitled "App Management system (AMS)", in which users can design their own light-wight software by adding controls like buttons, texts and etc at runtime. Furthermore, users can also add some behaviors to their GUI. The AMS should have an ability to generate .exe file or other executable file like jar from the user define mini software. So, i need to create some javafx project at runtime, i am grateful if someone can guide me to do so.