Search Results

Search found 1787 results on 72 pages for 'reflection emit'.

Page 6/72 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Java Generic Type and Reflection

    - by Tom Tucker
    I have some tricky generic type problem involving reflection. Here's the code. public @interface MyConstraint { Class<? extends MyConstraintValidator<?>> validatedBy(); } public interface MyConstraintValidator<T extends Annotation> { void initialize(T annotation); } /** @param annotation is annotated with MyConstraint. */ public void run(Annotation annotation) { Class<? extends MyConstraintValidator<? extends Annotation>> validatorClass = annotation.annotationType().getAnnotation(MyConstraint.class).validatedBy(); validatorClass.newInstance().initialize(annotation) // will not compile! } The run() method above will not compile because of the following error. The method initialize(capture#10-of ? extends Annotation) in the type MyConstraintValidator<capture#10-of ? extends Annotation> is not applicable for the arguments (Annotation) If I remove the wild cards, then it compiles and works fine. What would be the propert way to declare the type parameter for the vairable validatorClass? Thanks.

    Read the article

  • Reflection and Operator Overloads in C#

    - by TenshiNoK
    Here's the deal. I've got a program that will load a given assembly, parse through all Types and their Members and compile a TreeView (very similar to old MSDN site) and then build HTML pages for each node in the TreeView. It basically takes a given assembly and allows the user to create their own MSDN-like library for it for documentation purposes. Here's the problem I've run into: whenever an operator overload is encounted in a defined class, reflection returns that as a "MethodInfo" with the name set to something like "op_Assign" or "op_Equality". I want to be able to capture these and list them properly, but I can't find anything in the MethodInfo object that is returned to accurately identify that I'm looking at an operator. I definitely don't want to just capture everything that starts with "op_", since that will most certainly (at some point) will pick up a method it's not supposed to. I know that other methods and properties that are "special cases" like this one have the "IsSpecialName" property set, but appearantly that's not the case with operators. I've been scouring the 'net and wracking my brain to two days trying to figure this one out, so any help will be greatly appreciated.

    Read the article

  • Invoking public method on a class in a different package via reflection

    - by KARASZI István
    I ran into the following problem. I have two different packages in package a I would like to call the implemented method of an interface in a package b but the implementing class has package visibility. So a simplifed code looks like this: package b; public final class Factory { public static B createB() { return new ImplB(); } public interface B { void method(); } static class ImplB implements B { public void method() { System.out.println("Called"); } } } and the Invoker: package a; import java.lang.reflect.Method; import b.Factory; import b.Factory.B; public final class Invoker { private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[] {}; private static final Object[] EMPTY_OBJECT_ARRAY = new Object[] {}; public static void main(String... args) throws Exception { final B b = Factory.createB(); b.method(); final Method method = b.getClass().getDeclaredMethod("method", EMPTY_CLASS_ARRAY); method.invoke(b, EMPTY_OBJECT_ARRAY); } } When I start the program it prints out Called as expected and throws an Exception because the package visibility prohibits the calling of the discovered method. So my question is any way to solve this problem? Am I missing something in Java documentation or this is simply not possible although simply calling an implemented method is possible without reflection.

    Read the article

  • How to filter List<T> with LINQ and Reflection

    - by Ehsan Sajjad
    i am getting properties via reflection and i was doing like this to iterate on the list. private void HandleListProperty(object oldObject, object newObject, string difference, PropertyInfo prop) { var oldList = prop.GetValue(oldObject, null) as IList; var newList = prop.GetValue(newObject, null) as IList; if (prop.PropertyType == typeof(List<DataModel.ScheduleDetail>)) { List<DataModel.ScheduleDetail> ScheduleDetailsOld = oldList as List<DataModel.ScheduleDetail>; List<DataModel.ScheduleDetail> ScheduleDetailsNew = newList as List<DataModel.ScheduleDetail>; var groupOldSchedules = ScheduleDetailsOld .GroupBy(x => x.HomeHelpID) .SelectMany(s => s.DistinctBy(d => d.HomeHelpID) .Select(h => new { h.HomeHelpID, h.HomeHelpName })); } } Now i am making it generic because there will be coming different types of Lists and i don't want to put if conditions this way i want to write generic code to handle any type of list. I came up with this way: private void HandleListProperty(object oldObject, object newObject, string difference, PropertyInfo prop) { var oldList = prop.GetValue(oldObject, null) as IList; var newList = prop.GetValue(newObject, null) as IList; var ListType = prop.PropertyType; var MyListInstance = Activator.CreateInstance(ListType); MyListInstance = oldList; } i am able to get the items in MyListInstance but as the type will come at runtime i am not getting how to write linq query to filter them, any ideah how to do.

    Read the article

  • C# Reflection StackTrack get value

    - by John
    I'm making pretty heavy use of reflection in my current project to greatly simplify communication between my controllers and the wcf services. What I want to do now is to obtain a value from the Session within an object that has no direct access to HttpSessionStateBase (IE: Not a controller). For example, a ViewModel. I could pass it in or pass a reference to it etc. but that is not optimal in my situation. Since everything comes from a Controller at some point in my scenario I can do the following to walk the sack to the controller where the call originated, pretty simple stuff: var trace = new System.Diagnostics.StackTrace(); foreach (var frame in trace.GetFrames()) { var type = frame.GetMethod().DeclaringType; var prop = type.GetProperty("Session"); if(prop != null) { // not sure about this part... var value = prop.GetValue(type, null); break; } } The trouble here is that I can't seem to work out how to get the "instance" of the controller or the Session property so that I can read from it.

    Read the article

  • Unable to cast lists with Reflection in C#

    - by DrLazer
    I am having a lot of trouble with Reflection in C# at the moment. The app I am writing allows the user to modify the attributes of certain objects using a config file. I want to be able to save the object model (users project) to XML. The function below is called in the middle of a foreach loop, looping through a list of objects that contain all the other objects in the project within them. The idea is, that it works recursively to translate the object model into XML. Dont worry about the call to "Unreal" that just modifes the name of the objects slightly if they contain certain words. private void ReflectToXML(object anObject, XmlElement parentElement) { Type aType = anObject.GetType(); XmlElement anXmlElement = m_xml.CreateElement(Unreal(aType.Name)); parentElement.AppendChild(anXmlElement); PropertyInfo[] pinfos = aType.GetProperties(); //loop through this objects public attributes foreach (PropertyInfo aInfo in pinfos) { //if the attribute is a list Type propertyType = aInfo.PropertyType; if ((propertyType.IsGenericType)&&(propertyType.GetGenericTypeDefinition() == typeof(List<>))) { List<object> listObjects = (aInfo.GetValue(anObject,null) as List<object>); foreach (object aListObject in listObjects) { ReflectToXML(aListObject, anXmlElement); } } //attribute is not a list else anXmlElement.SetAttribute(aInfo.Name, ""); } } If an object attributes are just strings then it should be writing them out as string attributes in the XML. If an objects attributes are lists, then it should recursively call "ReflectToXML" passing itself in as a parameter, thereby creating the nested structure I require that nicely reflect the object model in memory. The problem I have is with the line List<object> listObjects = (aInfo.GetValue(anObject,null) as List<object>); The cast doesn't work and it just returns null. While debugging I changed the line to object temp = aInfo.GetValue(anObject,null); slapped a breakpoint on it to see what "GetValue" was returning. It returns a "Generic list of objects" Surely I should be able to cast that? The annoying thing is that temp becomes a generic list of objects but because i declared temp as a singular object, I can't loop through it because it has no Enumerator. How can I loop through a list of objects when I only have it as a propertyInfo of a class? I know at this point I will only be saving a list of empty strings out anyway, but thats fine. I would be happy to see the structure save out for now. Thanks in advance

    Read the article

  • Calling function dynamically by using Reflection

    - by Alaa'
    Hi, I'm generating dll files contain code like the following example : // using System; using System.Collections; using System.Xml; using System.IO; using System.Windows.Forms; namespace CSharpScripter { public class TestClass : CSharpScripter.Command { private int i=1; private int j=2; public int k=3; public TestClass6() { } public void display (int i,int j,int k) { string a = null; a= k.ToString(); string a1 = null; a1= this.i.ToString(); string a2 = null; a2= j.ToString(); MessageBox.Show(" working! "+ "k="+ a +" i="+a1 + " j="+ a2); } public void setValues(int i,int j,int k1) { this.i=i; this.j=j; k=k1; } // I'm compiling the pervious code, then I execute an object from the dll file. So, in the second part of the code ( Executing part), I'm just calling the execute function, It contains a call for a function, I named here: display. For that I need to set values in the declaration by a setValue function. I want it to been called dynamically (setValues ), which has declaration like : public void(Parameter[] parameters) { //some code block here } For this situation I used Reflection. // Type objectType = testClass.GetType(); MethodInfo members = objectType.GetMethod("setValues"); ParameterInfo[] parameters = members.GetParameters(); For) int t = 0; t < parameters.Length; t++) { If (parameters[t]. ParameterType == typeof()) { object value = this.textBox2.Text; parameters.SetValue)Convert.ChangeType(value,parameters[t].ParameterType), t); } } // But it throws an casting error" Object cannot be stored in an array of this type." at last line, in first parameter for (setValue) methode. What is the problem here? And How I can call the method Dynamically after the previous code, by( Invoke) or is there a better way? Thanks.

    Read the article

  • IL emit - operation could destabilize runtime when storing then loading

    - by Jakob Botsch Nielsen
    Hey, so I have the following IL: il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ret); Which works fine. It basically returns the argument given. This, however: il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); Does not work. It crashes with the exception "Operation could destabilize the runtime.". Now, I know that the purpose of that is useless but I'm trying to reach my goal by small steps. Why does that not work?

    Read the article

  • IL short-form instructions aren't short?

    - by Alix
    Hi. I was looking at the IL code of a valid method with Reflector and I've run into this: L_00a5: leave.s L_0103 Instructions with the suffix .s are supposed to take an int8 operand, and sure enough this is should be the case with Leave_S as well. However, 0x0103 is 259, which exceeds the capacity of an int8. The method somehow works, but when I read the instructions with method Mono.Reflection.Disassembler.GetInstructions it retrieves L_00a5: leave.s L_0003 that is, 3 instead of 259, because it's supposed to be an int8. So, my question: how is the original instruction (leave.s L_0103) possible? I have looked at the ECMA documentation for that (Partition III: CIL Instruction Set) and I can't find anything that explains it. Any ideas? Thanks.

    Read the article

  • Getting the constructor of an Interface Type through reflection, is there a better approach than loo

    - by Will Marcouiller
    I have written a generic type: IDirectorySource<T> where T : IDirectoryEntry, which I'm using to manage Active Directory entries through my interfaces objects: IGroup, IOrganizationalUnit, IUser. So that I can write the following: IDirectorySource<IGroup> groups = new DirectorySource<IGroup>(); // Where IGroup implements `IDirectoryEntry`, of course.` foreach (IGroup g in groups.ToList()) { listView1.Items.Add(g.Name).SubItems.Add(g.Description); } From the IDirectorySource<T>.ToList() methods, I use reflection to find out the appropriate constructor for the type parameter T. However, since T is given an interface type, it cannot find any constructor at all! Of course, I have an internal class Group : IGroup which implements the IGroup interface. No matter how hard I have tried, I can't figure out how to get the constructor out of my interface through my implementing class. [DirectorySchemaAttribute("group")] public interface IGroup { } internal class Group : IGroup { internal Group(DirectoryEntry entry) { NativeEntry = entry; Domain = NativeEntry.Path; } // Implementing IGroup interface... } Within the ToList() method of my IDirectorySource<T> interface implementation, I look for the constructor of T as follows: internal class DirectorySource<T> : IDirectorySource<T> { // Implementing properties... // Methods implementations... public IList<T> ToList() { Type t = typeof(T) // Let's assume we're always working with the IGroup interface as T here to keep it simple. // So, my `DirectorySchema` property is already set to "group". // My `DirectorySearcher` is already instantiated here, as I do it within the DirectorySource<T> constructor. Searcher.Filter = string.Format("(&(objectClass={0}))", DirectorySchema) ConstructorInfo ctor = null; ParameterInfo[] params = null; // This is where I get stuck for now... Please see the helper method. GetConstructor(out ctor, out params, new Type() { DirectoryEntry }); SearchResultCollection results = null; try { results = Searcher.FindAll(); } catch (DirectoryServicesCOMException ex) { // Handling exception here... } foreach (SearchResult entry in results) entities.Add(ctor.Invoke(new object() { entry.GetDirectoryEntry() })); return entities; } } private void GetConstructor(out ConstructorInfo constructor, out ParameterInfo[] parameters, Type paramsTypes) { Type t = typeof(T); ConstructorInfo[] ctors = t.GetConstructors(BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod); bool found = true; foreach (ContructorInfo c in ctors) { parameters = c.GetParameters(); if (parameters.GetLength(0) == paramsTypes.GetLength(0)) { for (int index = 0; index < parameters.GetLength(0); ++index) { if (!(parameters[index].GetType() is paramsTypes[index].GetType())) found = false; } if (found) { constructor = c; return; } } } // Processing constructor not found message here... } My problem is that T will always be an interface, so it never finds a constructor. Is there a better way than looping through all of my assembly types for implementations of my interface? I don't care about rewriting a piece of my code, I want to do it right on the first place so that I won't need to come back again and again and again. EDIT #1 Following Sam's advice, I will for now go with the IName and Name convention. However, is it me or there's some way to improve my code? Thanks! =)

    Read the article

  • Can't access CodeBase from a dynamically generated assembly.

    - by Michael Meadows
    I'm trying to create an assembly dynamically in .Net. I can't seem to figure out how to get the CodeBase property to return a value, however. Here's an example: var assemblyName = new AssemblyName { Name = "Whatever", CodeBase = Directory.GetCurrentDirectory() }; var assemblyBuilder = AppDomain.CurrentDomain .DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); var moduleBuilder = assemblyBuilder.DefineDynamicModule("WhateverModule", "Whatever.dll"); var typeBuilder = moduleBuilder.DefineType("WhateverType", TypeAttributes.Public); var type = typeBuilder.CreateType(); assemblyBuilder.Save("Whatever.dll"); var codeBase = type.Assembly.CodeBase; // throws the below exception System.NotSupportedException was unhandled Message=The invoked member is not supported in a dynamic assembly. Source=mscorlib StackTrace: at System.Reflection.Emit.InternalAssemblyBuilder.get_CodeBase() at Stupid.Program.Main(String[] args) in C:\Users\Walking Disaster\Documents\Visual Studio 10\Projects\Lingual.Proxy\Stupid\Program.cs:line 25 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() Can anyone see what I'm doing wrong?

    Read the article

  • actionscript3: reflect-class applied on rotationY

    - by algro
    Hi, I'm using a class which applies a visual reflection-effect to defined movieclips. I use a reflection-class from here: link to source. It works like a charm except when I apply a rotation to the movieclip. In my case the reflection is still visible but only a part of it. What am I doing wrong? How could I pass/include the rotation to the Reflection-Class ? Thanks in advance! This is how you apply the Reflection Class to your movieclip: var ref_mc:MovieClip = new MoviClip(); addChild(ref_mc); var r1:Reflect = new Reflect({mc:ref_mc, alpha:50, ratio:50,distance:0, updateTime:0,reflectionDropoff:1}); Now I apply a rotation to my movieclip: ref_mc.rotationY = 30; And Here the Reflect-Class: package com.pixelfumes.reflect{ import flash.display.MovieClip; import flash.display.DisplayObject; import flash.display.BitmapData; import flash.display.Bitmap; import flash.geom.Matrix; import flash.display.GradientType; import flash.display.SpreadMethod; import flash.utils.setInterval; import flash.utils.clearInterval; public class Reflect extends MovieClip{ //Created By Ben Pritchard of Pixelfumes 2007 //Thanks to Mim, Jasper, Jason Merrill and all the others who //have contributed to the improvement of this class //static var for the version of this class private static var VERSION:String = "4.0"; //reference to the movie clip we are reflecting private var mc:MovieClip; //the BitmapData object that will hold a visual copy of the mc private var mcBMP:BitmapData; //the BitmapData object that will hold the reflected image private var reflectionBMP:Bitmap; //the clip that will act as out gradient mask private var gradientMask_mc:MovieClip; //how often the reflection should update (if it is video or animated) private var updateInt:Number; //the size the reflection is allowed to reflect within private var bounds:Object; //the distance the reflection is vertically from the mc private var distance:Number = 0; function Reflect(args:Object){ /*the args object passes in the following variables /we set the values of our internal vars to math the args*/ //the clip being reflected mc = args.mc; //the alpha level of the reflection clip var alpha:Number = args.alpha/100; //the ratio opaque color used in the gradient mask var ratio:Number = args.ratio; //update time interval var updateTime:Number = args.updateTime; //the distance at which the reflection visually drops off at var reflectionDropoff:Number = args.reflectionDropoff; //the distance the reflection starts from the bottom of the mc var distance:Number = args.distance; //store width and height of the clip var mcHeight = mc.height; var mcWidth = mc.width; //store the bounds of the reflection bounds = new Object(); bounds.width = mcWidth; bounds.height = mcHeight; //create the BitmapData that will hold a snapshot of the movie clip mcBMP = new BitmapData(bounds.width, bounds.height, true, 0xFFFFFF); mcBMP.draw(mc); //create the BitmapData the will hold the reflection reflectionBMP = new Bitmap(mcBMP); //flip the reflection upside down reflectionBMP.scaleY = -1; //move the reflection to the bottom of the movie clip reflectionBMP.y = (bounds.height*2) + distance; //add the reflection to the movie clip's Display Stack var reflectionBMPRef:DisplayObject = mc.addChild(reflectionBMP); reflectionBMPRef.name = "reflectionBMP"; //add a blank movie clip to hold our gradient mask var gradientMaskRef:DisplayObject = mc.addChild(new MovieClip()); gradientMaskRef.name = "gradientMask_mc"; //get a reference to the movie clip - cast the DisplayObject that is returned as a MovieClip gradientMask_mc = mc.getChildByName("gradientMask_mc") as MovieClip; //set the values for the gradient fill var fillType:String = GradientType.LINEAR; var colors:Array = [0xFFFFFF, 0xFFFFFF]; var alphas:Array = [alpha, 0]; var ratios:Array = [0, ratio]; var spreadMethod:String = SpreadMethod.PAD; //create the Matrix and create the gradient box var matr:Matrix = new Matrix(); //set the height of the Matrix used for the gradient mask var matrixHeight:Number; if (reflectionDropoff<=0) { matrixHeight = bounds.height; } else { matrixHeight = bounds.height/reflectionDropoff; } matr.createGradientBox(bounds.width, matrixHeight, (90/180)*Math.PI, 0, 0); //create the gradient fill gradientMask_mc.graphics.beginGradientFill(fillType, colors, alphas, ratios, matr, spreadMethod); gradientMask_mc.graphics.drawRect(0,0,bounds.width,bounds.height); //position the mask over the reflection clip gradientMask_mc.y = mc.getChildByName("reflectionBMP").y - mc.getChildByName("reflectionBMP").height; //cache clip as a bitmap so that the gradient mask will function gradientMask_mc.cacheAsBitmap = true; mc.getChildByName("reflectionBMP").cacheAsBitmap = true; //set the mask for the reflection as the gradient mask mc.getChildByName("reflectionBMP").mask = gradientMask_mc; //if we are updating the reflection for a video or animation do so here if(updateTime > -1){ updateInt = setInterval(update, updateTime, mc); } } public function setBounds(w:Number,h:Number):void{ //allows the user to set the area that the reflection is allowed //this is useful for clips that move within themselves bounds.width = w; bounds.height = h; gradientMask_mc.width = bounds.width; redrawBMP(mc); } public function redrawBMP(mc:MovieClip):void { // redraws the bitmap reflection - Mim Gamiet [2006] mcBMP.dispose(); mcBMP = new BitmapData(bounds.width, bounds.height, true, 0xFFFFFF); mcBMP.draw(mc); } private function update(mc):void { //updates the reflection to visually match the movie clip mcBMP = new BitmapData(bounds.width, bounds.height, true, 0xFFFFFF); mcBMP.draw(mc); reflectionBMP.bitmapData = mcBMP; } public function destroy():void{ //provides a method to remove the reflection mc.removeChild(mc.getChildByName("reflectionBMP")); reflectionBMP = null; mcBMP.dispose(); clearInterval(updateInt); mc.removeChild(mc.getChildByName("gradientMask_mc")); } } }

    Read the article

  • Is it bad practice to use Reflection in Unit testing?

    - by Sebi
    During the last years I always thought that in Java, Reflection is widely used during Unit testing. Since some of the variables/methods which have to be checked are private, it is somehow necessary to read the values of them. I always thought that the Reflection API is also used for this purpose. Last week i had to test some packages and therefore write some JUnit tests. As always i used Reflection to access private fields and methods. But my supervisor who checked the code wasn't really happy with that and told me that the Reflection API wasn't meant to use for such "hacking". Instead he suggested to modifiy the visibility in the production code. Is it really bad practice to use Reflection? I can't really believe that

    Read the article

  • determine complex type from a primitive type using reflection

    - by Nilotpal Das
    I am writing a tool where I need to reflect upon methods and if the parameters of the methods are complex type, then I need to certain type of actions such as instantiating them etc. Now I saw the IsPrimitive property in the Type variable. However, it shows string and decimal as complex types, which technically isn't incorrect. However what I really want is to be able to distinguish developer created class types from system defined data types. Is there any way that I can do this?

    Read the article

  • C# - Recursive / Reflection Property Values

    - by tyndall
    What is the best way to go about this in C#? string propPath = "ShippingInfo.Address.Street"; I'll have a property path like the one above read from a mapping file. I need to be able to ask the Order object what the value of the code below will be. this.ShippingInfo.Address.Street Balancing performance with elegance. All object graph relationships should be one-to-one. Part 2: how hard would it be to add in the capability for it to grab the first one if its a List< or something like it.

    Read the article

  • IEnumerable<T> and reflection

    - by Aren B
    Background Working in .NET 2.0 Here, reflecting lists in general. I was originally using t.IsAssignableFrom(typeof(IEnumerable)) to detect if a Property I was traversing supported the IEnumerable Interface. (And thus I could cast the object to it safely) However this code was not evaluating to True when the object is a BindingList<T>. Next I tried to use t.IsSubclassOf(typeof(IEnumerable)) and didn't have any luck either. Code /// <summary> /// Reflects an enumerable (not a list, bad name should be fixed later maybe?) /// </summary> /// <param name="o">The Object the property resides on.</param> /// <param name="p">The Property We're reflecting on</param> /// <param name="rla">The Attribute tagged to this property</param> public void ReflectList(object o, PropertyInfo p, ReflectedListAttribute rla) { Type t = p.PropertyType; //if (t.IsAssignableFrom(typeof(IEnumerable))) if (t.IsSubclassOf(typeof(IEnumerable))) { IEnumerable e = p.GetValue(o, null) as IEnumerable; int count = 0; if (e != null) { foreach (object lo in e) { if (count >= rla.MaxRows) break; ReflectObject(lo, count); count++; } } } } The Intent I want to basically tag lists i want to reflect through with the ReflectedListAttribute and call this function on the properties that has it. (Already Working) Once inside this function, given the object the property resides on, and the PropertyInfo related, get the value of the property, cast it to an IEnumerable (assuming it's possible) and then iterate through each child and call ReflectObject(...) on the child with the count variable.

    Read the article

  • System.Reflection and InvokeMember, storing type, assembly, and object in a class

    - by Cyclone
    I have tested code to call a method inside of a compiled DLL, and it works. I created a class to store the object, type, and loaded assembly, but something is lost in translation because it is unable to find the member I wish to invoke. If I create a type, object, and assembly, and properly load everything into these and perform InvokeMember on the type, it works just fine. However, when I use the things inside of my class, it throws a MissingMemberException and does not invoke the member, obviously. What am I doing wrong? The member in question is a subroutine which takes one argument, a string. This is quite frustrating. Code being called: Dim MyLoadedAssembly As New LoadedAssembly() MyLoadedAssembly.MyAssembly = Assembly.LoadFrom("display.dll") MyLoadedAssembly.MyObject = MyLoadedAssembly.MyAssembly.CreateInstance("Display.UI.Window") MyLoadedAssembly.MyType = MyLoadedAssembly.MyAssembly.GetType("Display.UI.Window") Dim args() As Object = {"test"} MyLoadedAssembly.InvokeMember("Show", args) Private Class LoadedAssembly Public MyType As Type Public MyObject As Object Public MyAssembly As Assembly Public Function InvokeMember(ByVal name As String, ByVal args() As Object) Return MyType.InvokeMember(name, BindingFlags.Default Or BindingFlags.InvokeMethod Or BindingFlags.GetProperty Or BindingFlags.Instance, Nothing, MyObject, args) End Function End Class Code inside of display.dll: Namespace UI Public Class Window Private wind As New System.Windows.Forms.Form Public FullScreen As Boolean = False Public Overloads Sub Show(ByVal text As String) wind.Show() wind.Text = text End Sub Public Overloads Sub Show() wind.Show() End Sub End Class End Namespace The root namespace for display.dll is Display. Why is my code only working when not within this class? System.MissingMethodException was unhandled Message="Method 'Display.UI.Window.Show' not found." Source="mscorlib" StackTrace: at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args) at IDE.IDE.LoadedAssembly.InvokeMember(String name, Object[] args) in C:\Documents and Settings\Davey\Desktop\RaptorScript\RaptorScript\RaptorScript\IDE.vb:line 69 at IDE.IDE.IDE_Load(Object sender, EventArgs e) in C:\Documents and Settings\Davey\Desktop\RaptorScript\RaptorScript\RaptorScript\IDE.vb:line 50 at System.EventHandler.Invoke(Object sender, EventArgs e) at System.Windows.Forms.Form.OnLoad(EventArgs e) at System.Windows.Forms.Form.OnCreateControl() at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible) at System.Windows.Forms.Control.CreateControl() at System.Windows.Forms.Control.WmShowWindow(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.ContainerControl.WndProc(Message& m) at System.Windows.Forms.Form.WmShowWindow(Message& m) at System.Windows.Forms.Form.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow) at System.Windows.Forms.Control.SetVisibleCore(Boolean value) at System.Windows.Forms.Form.SetVisibleCore(Boolean value) at System.Windows.Forms.Control.set_Visible(Boolean value) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(ApplicationContext context) at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine) at IDE.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:

    Read the article

  • Objective-C runtime reflection (objc_msgSend): does it violate the iPhone Developer License Agreemen

    - by GamingHorror
    Does code like this (potentially) violate the iPhone Developer License Agreement? Class clazz = NSClassFromString(@"WNEntity"); id entity = [clazz entityWithImage:@"Icon.png"]; SEL setPositionSelector = NSSelectorFromString(@"setPosition:"); objc_msgSend(entity, setPositionSelector, CGPointMake(200, 100)); I'm working on code that dynamically allocates classes from XML and calls methods on them via objc_msgSend. It's just very convenient constructing my objects that way but it worries me because i have no idea whether this is ok or violates the License by dynamically executing code or maybe even calling private (?) API functions. They wouldn't be documented if they were private, right? Can someone shed some light on this? Have you had an App approved or rejected using code similar to the above? I'm pretty sure that this is ok but i wan't to hear it from someone else! :)

    Read the article

  • Getting Nested Object Property Value Using Reflection

    - by Kumar
    I have the following two classes: public class Address { public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } } public class Employee { public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public Address EmployeeAddress { get; set; } } I have an instance of the employee class as follows: var emp1Address = new Address(); emp1Address.AddressLine1 = "Microsoft Corporation"; emp1Address.AddressLine2 = "One Microsoft Way"; emp1Address.City = "Redmond"; emp1Address.State = "WA"; emp1Address.Zip = "98052-6399"; var emp1 = new Employee(); emp1.FirstName = "Bill"; emp1.LastName = "Gates"; emp1.EmployeeAddress = emp1Address; I have a method which gets the property value based on the property name as follows: public object GetPropertyValue(object obj ,string propertyName) { var objType = obj.GetType(); var prop = objType.GetProperty(propertyName); return prop.GetValue(obj, null); } The above method works fine for calls like GetPropertyValue(emp1, "FirstName") but if I try GetPropertyValue(emp1, "Address.AddressLine1") it throws an exception because objType.GetProperty(propertyName); is not able to locate the nested object property value. Is there a way to fix this?

    Read the article

  • Using reflection to retrieve constructor used to instantiate attribute

    - by summatix
    How can I retrieve information about how an attribute was instantiated? Consider I have the following class definitions: [AttributeUsage(AttributeTargets.Class)] public class ExampleAttribute : Attribute { public ExampleAttribute(string value) { Value = value; } public string Value { get; private set; } } [ExampleAttribute("test")] public class Test { } The new .NET 4.0 MemberInfo.GetCustomAttributesData method: foreach (var attribute in typeof(Test).GetCustomAttributesData()) { Console.WriteLine(attribute); } outputs [Example.ExampleAttribute("test")]. Is there another way to retrieve this same information, preferably using the MemberInfo.GetCustomAttributes method?

    Read the article

  • Reflection, get DataAnnotation attributes from buddy class.

    - by Feryt
    Hi. I need to check if property has specific attribute defined in its buddy class: [MetadataType(typeof(Metadata))] public sealed partial class Address { private sealed class Metadata { [Required] public string Address1 { get; set; } [Required] public string Zip { get; set; } } } How to check what properties has defined Required attribute? Thank you.

    Read the article

  • How to work with varargs and reflection

    - by PeterMmm
    Simple question, how make this code working ? public class T { public static void main(String[] args) throws Exception { new T().m(); } public // as mentioned by Bozho void foo(String... s) { System.err.println(s[0]); } void m() throws Exception { String[] a = new String[]{"hello", "kitty"}; System.err.println(a.getClass()); Method m = getClass().getMethod("foo", a.getClass()); m.invoke(this, (Object[]) a); } } Output: class [Ljava.lang.String; Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597)

    Read the article

  • Reflection and changing a variables type at runtime?

    - by james-west
    Hi I'm trying to create an object Of a specific type. I've got the following code, but it fails because it can't cast the new table object to the one that is already defined. I need table to start of an IEnumerable type so I can't declare is an object. Public sub getTable(ByVal t as Type) Dim table As Table(Of Object) Dim tableType As Type = GetType(Table(Of )).MakeGenericType(t) table = FormatterServices.GetUninitializedObject(tableType) End sub So in short - is there a way of changing a variable type at runtime? (or a better way of doing what I'm doing) Thanks in advance. James

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >