Search Results

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

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

  • .NET 2.0: Invoking Methods Using Reflection And Generics Causes Exception

    - by David Derringer
    Hi all, I'm new to Stack Overflow, so forgive me. I've just started transititoning over to C# and I am stuck on a problem. I am wanting to pass a generic class in and call a method from that class. So, my code looks as such: public void UpdateRecords<T>(T sender) where T : new() //where T: new() came from Resharper { Type foo = Type.GetType(sender.GetType().ToString()); object[] userParameters = new object[2]; userParameters[0] = x; userParameters[1] = y; sender = new T(); //This was to see if I could solve my exception problem MethodInfo populateRecord = foo.GetMethod("MethodInOtherClass"); populateMethod.Invoke(sender, userParameters); } Exception thrown: "Object reference not set to an instance of an object." Again, I really apologize, as I am nearly brand new to C# and this is the first time I've ever handled reflection and generics. Thank you!

    Read the article

  • Reflection: take values from an unknown running alpplication

    - by Dr.Lesh
    I'm writing an application that searchs for Semaphore types in the fields of unknown classes in unknown application (passed by user). I made it using Reflection and it worked. Now I want to fill up these semaphores with values, taking them from a running instance of this unknown application. So i took the class with "main" method of this unknown application, made a newInstance, and passed it when invoking the main method to start the application: Class mainClass = getItSomeWhere(); Object instance = mainClass.newInstance(); Method mainMethod = mainClass.getDeclaredMethod("main", new Class[]{String[].class}); mainMethod.invoke(instance, new Object[]{args}); and it worked fine. Now, how can I get the semaphore values, taking them from the classes of this running application, when I only have an instance of the main class? Many thanks for the answers.

    Read the article

  • Creating dynamic generics at runtime using Reflection

    - by MPhlegmatic
    I'm trying to convert a Dictionary< dynamic, dynamic to a statically-typed one by examining the types of the keys and values and creating a new Dictionary of the appropriate types using Reflection. If I know the key and value types, I can do the following: Type dictType = typeof(Dictionary<,>); newDict = Activator.CreateInstance(dictType.MakeGenericType(new Type[] { keyType, valueType })); However, I may need to create, for example, a Dictionary< MyKeyType, dynamic if the values are not all of the same type, and I can't figure out how to specify the dynamic type, since typeof(dynamic) isn't viable. How would I go about doing this, and/or is there a simpler way to accomplish what I'm trying to do?

    Read the article

  • Calling a static Func from a static class using reflection

    - by ChrisO
    Given the static class: public static class Converters { public static Func<Int64, string> Gold = c => String.Format("{0}g {1}s {2}c", c/10000, c/100%100, c%100); } I am receiving the Func name from a database as a string (regEx.Converter). How can I invoke the Gold Func using reflection? Here is what I have so far: var converter = typeof(Converters).GetMember(regEx.Converter); if (converter.Count() != 0) { //throw new ConverterNotFoundException; } matchedValue = converter.Invoke(null, new object[]{matchedValue}) as string;

    Read the article

  • Java Interface Reflection Alternatives

    - by Phaedrus
    I am developing an application that makes use of the Java Interface as more than a Java interface, i.e., During runtime, the user should be able to list the available methods within the interface class, which may be anything: private Class<? extends BaseInterface> interfaceClass. At runtime, I would like to enum the available methods, and then based on what the user chooses, invoke some method. My question is: Does the Java "Interface" architecture provide any method for me to peek and invoke methods without using the Reflection API? I wish there were something like this (Maybe there is): private Interface<? extends BaseInterface> interfaceAPI; public void someMethod(){ interfaceAPI.listMethods(); interfaceAPI.getAnnotations(); } Maybe there is some way to use Type Generics to accomplish what I want? Thanks, Phaedrus

    Read the article

  • How to convert objects in reflection (Linq to XML)

    - by user829174
    I have the following code which is working fine, the code creates plugins in reflection via run time: using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Xml.Linq; using System.Reflection; using System.Text; namespace WindowsFormsApplication1 { public abstract class Plugin { public string Type { get; set; } public string Message { get; set; } } public class FilePlugin : Plugin { public string Path { get; set; } } public class RegsitryPlugin : Plugin { public string Key { get; set; } public string Name { get; set; } public string Value { get; set; } } static class MyProgram { [STAThread] static void Main(string[] args) { string xmlstr =@" <Client> <Plugin Type=""FilePlugin""> <Message>i am a file plugin</Message> <Path>c:\</Path> </Plugin> <Plugin Type=""RegsitryPlugin""> <Message>i am a registry plugin</Message> <Key>HKLM\Software\Microsoft</Key> <Name>Version</Name> <Value>3.5</Value> </Plugin> </Client> "; Assembly asm = Assembly.GetExecutingAssembly(); XDocument xDoc = XDocument.Load(new StringReader(xmlstr)); Plugin[] plugins = xDoc.Descendants("Plugin") .Select(plugin => { string typeName = plugin.Attribute("Type").Value; var type = asm.GetTypes().Where(t => t.Name == typeName).First(); Plugin p = Activator.CreateInstance(type) as Plugin; p.Type = typeName; foreach (var prop in plugin.Descendants()) { var pi = type.GetProperty(prop.Name.LocalName); object newVal = Convert.ChangeType(prop.Value, pi.PropertyType); pi.SetValue(p, newVal, null); } return p; }).ToArray(); // //"plugins" ready to use // } } } I am trying to modify the code and adding new class named DetailedPlugin so it will be able to read the following xml: string newXml = @" <Client> <Plugin Type=""FilePlugin""> <Message>i am a file plugin</Message> <Path>c:\</Path> <DetailedPlugin Type=""DetailedFilePlugin""> <Message>I am a detailed file plugin</Message> </DetailedPlugin> </Plugin> <Plugin Type=""RegsitryPlugin""> <Message>i am a registry plugin</Message> <Key>HKLM\Software\Microsoft</Key> <Name>Version</Name> <Value>3.5</Value> <DetailedPlugin Type=""DetailedRegsitryPlugin""> <Message>I am a detailed registry plugin</Message> </DetailedPlugin> </Plugin> </Client> "; for this i modified my classes to the following: public abstract class Plugin { public string Type { get; set; } public string Message { get; set; } public DetailedPlugin DetailedPlugin { get; set; } // new } public class FilePlugin : Plugin { public string Path { get; set; } } public class RegsitryPlugin : Plugin { public string Key { get; set; } public string Name { get; set; } public string Value { get; set; } } // new classes: public abstract class DetailedPlugin { public string Type { get; set; } public string Message { get; set; } } public class DetailedFilePlugin : Plugin { public string ExtraField1 { get; set; } } public class DetailedRegsitryPlugin : Plugin { public string ExtraField2{ get; set; } } from here i need some help to accomplish reading the xml and create the plugins with the nested DetailedPlugin

    Read the article

  • Protect value from changies using reflection?

    - by IordanTanev
    Hi, here is the problem case i am writing a little third party library. In this library i have a class like this public class TestClass { public int TestField { get; private set; } public TestClass( ) { TestField = 1; } } Then i have a varialbe form this class like this public TestClass test = new TestClass( ); The problem i am facing is that usnig reflection like this PropertyInfo field = typeof( TestClass ).GetProperty( "TestField" ); field.SetValue( test, 2, null ); programers can change internal value of this class. this will be very bad thing becouse it can crash the hole library. My question is what is the best way to protect my code form such changes.I know i can use some kind of bool flag so tha value can be changed only ones but this is not very good salution is there a better one? Best Regards, Iordan

    Read the article

  • Reflection for Class of generic parameter in Java?

    - by hatboysam
    Imagine the following scenario: class MyClass extends OtherClass<String>{ String myName; //Whatever } class OtherClass<T> { T myfield; } And I am analyzing MyClass using reflection specifically (MyClass.class).getDeclaredFields(), in this case I will get the following fields (and Types, using getType() of the Field): myName --> String myField --> T I want to get the actual Type for T, which is known at runtime due to the explicit "String" in the extends notation, how do I go about getting the non-genetic type of myField?

    Read the article

  • Best way of invoking getter by reflection

    - by Javi
    Hello, I need to get the value of a field with a specific annotation, So with reflection I am able to get this Field Object. The problem is that this field will be always private though I know in advance it will always have a getter method. I know that I can use setAccesible(true) and get its value (when there is no PermissionManager), though I prefer to invoke its getter method. I know that I could look for the method by looking for "get+fieldName" (though I know for example for boolean fields are sometimes named as "is+fieldName"). I wonder if there is a better way to invoke this getter (many frameworks use getters/setters to access the attributes so maybe they do in another way). Thanks

    Read the article

  • Reflection alternative for switch on enum in order to select namespace/class

    - by Am
    Hi, I have an interface named IHarvester. There are 3 implementations of that interface, each under their own namespace: Google Yahoo Bing A HarvesterManager uses the given harvester. It knows the interface and all 3 implementations. I want some way of letting the class user say in which harvester it wants to use. And in the code select that implementation, without a switch-case implementation. Can reflection save my day? Here is the code bits: // repeat for each harvester namespace Harvester.Google { public abstract class Fetcher : BaseHarvester, IInfoHarvester {...} } public enum HarvestingSource { Google, Yahoo, Bing, } class HarvesterManager { public HarvestingSource PreferedSource {get;set;} public HarvestSomthing() { switch (PreferedSource) .... // awful... } } Thanks. I will give my 2 cents of why I want to change this. There several people writing harvesters, I want them to focus only on building more harvesters, without ever needing to update the enum, or at worst, update only the enum.

    Read the article

  • Rails Associations - Callback Sequence/Magic

    - by satynos
    Taking following association declaration as an example: class Post has_many :comments end Just by declaring the has_many :comments, ActiveRecord adds several methods of which I am particularly interested in comments which returns array of comments. I browsed through the code and following seems to be the callback sequence: def has_many(association_id, options = {}, &extension) reflection = create_has_many_reflection(association_id, options, &extension) configure_dependency_for_has_many(reflection) add_association_callbacks(reflection.name, reflection.options) if options[:through] collection_accessor_methods(reflection, HasManyThroughAssociation) else collection_accessor_methods(reflection, HasManyAssociation) end end def collection_accessor_methods(reflection, association_proxy_class, writer = true) collection_reader_method(reflection, association_proxy_class) if writer define_method("#{reflection.name}=") do |new_value| # Loads proxy class instance (defined in collection_reader_method) if not already loaded association = send(reflection.name) association.replace(new_value) association end define_method("#{reflection.name.to_s.singularize}_ids=") do |new_value| ids = (new_value || []).reject { |nid| nid.blank? } send("#{reflection.name}=", reflection.class_name.constantize.find(ids)) end end end def collection_reader_method(reflection, association_proxy_class) define_method(reflection.name) do |*params| force_reload = params.first unless params.empty? association = association_instance_get(reflection.name) unless association association = association_proxy_class.new(self, reflection) association_instance_set(reflection.name, association) end association.reload if force_reload association end define_method("#{reflection.name.to_s.singularize}_ids") do if send(reflection.name).loaded? || reflection.options[:finder_sql] send(reflection.name).map(&:id) else send(reflection.name).all(:select => "#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").map(&:id) end end end In this sequence of callbacks, where exactly is the actual SQL being executed for retrieving the comments when I do @post.comments ?

    Read the article

  • dll's loaded through reflection - Phantom Bug

    - by Seattle Leonard
    Ok, I got a strange one here and I want to know if any of you have ever run accross anything like it. So I've got this web app that loads up a bunch of dll's through reflection. Basically it looks for Types that are derived from certain abstract types and adds them to the list of things it can make. Here's the weird part. While developing there is never a problem. When installing it, there is never a problem to start with. Then, at a seemingly random time, the application breaks while trying to find all the types. I've had 2 sites sitting side by side and one worked while the other did not, and they were configured exactly(and I mean exactly) the same. IISRESET's never helped, but this did: I simply moved all the dll's out of the bin directory then moved them back. That's right I just moved them out of the bin directory then put them right back where they came from and everything worked fine. Any ideas? Got some more info When the site is working I notice this behavior: After IISRESET it still works, but recycling the app pool will cause it to break. When the site is broken: Neiter IISRESET nor recycling the app pool fixes it, but moving a single dll out then back in fixes it.

    Read the article

  • How to simply a foreach iteration using reflection

    - by Priya
    Consider that I have to get the overall performance of X. X has Y elements and Y in turn has Z elements which inturn has some N elements. To get the performance of X I do this: List<double> XQ = new List<double>(); foreach (Elem Y in X.Y){ List<double> YQ = new List<double>(); foreach (Elem Z in Y.Z){ List<double> ZQ = new List<double>(); foreach (Elem N in Z.N){ ZQ.Add(GetPerformance(N)); } YQ.Add(AVG(ZQ)); } XQ.Add(AVG(YQ)); } AVG of XQ list gives the performance of X. The performance can be calculated for either X or Y or for Z. X, Y and Z share the same base class. So depending on the item given the foreach loop has to be executed. Currently I have a switch case to determine each item (X or Y or Z) and the foreach loop is repeated in the code pertaining to the item (eg. If Y foreach starts from Y.Z). Is is possible to convert this whole code generic using reflection instead of having to repeat it in each switch case? Thanks

    Read the article

  • VB.NET, templates, reflection, inheritance, feeling adrift

    - by brovar
    I've just made myself up a problem and am now wondering how to solve it. To begin with, I'm using some third-party components, including some calendar controls like schedule and timeline. They're used in the project classes more or less like that: Friend Class TimeBasedDataView 'some members End Class Friend Class ScheduleDataView Inherits TimeBasedDataView Public Schedule As Controls.Schedule.Schedule 'and others End Class Friend Class TimeLineDataView Inherits TimeBasedDataView Public TimeLine As Controls.TimeLine.TimeLine 'and others End Class (Hmm, code coloring fail, never mind...) Now, to allow managing the look of data being presented there are some mechanisms including so called Style Managers. A lot of code in them repeats, varying almost only with the control it maintains: Friend Class TimeLineStyleManager Private m_TimeLine As TimeLineDataView Private Sub Whatever() m_TimeLine.TimeLine.SomeProperty = SomeValue End Sub End Class Friend Class ScheduleStyleManager Private m_Schedule As ScheduleDataView Private Sub Whatever() m_Schedule.Schedule.SomeProperty = SomeValue End Sub End Class I was wondering if I could create some base class for those managers, like Friend Class TimeBasedCtrlStyleManagerBase(Of T As TimeBasedDataView) Private m_Control As T 'and others End Class which would unify these two, but I've got lost when it came to maintaining two components that have nothing in common (except their properties' names, etc.). Type reflection maybe? I'll be grateful for any advice ;)

    Read the article

  • C# Reflection StackTrace 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

  • Calling MethodBase's Invoke on a constructor (reflection)

    - by Alix
    Hi everyone. First of all, sorry if this has been asked before. I've done a pretty comprehensive search and found nothing quite like it, but I may have missed something. And now to the question: I'm trying to invoke a constructor through reflection, with no luck. Basically, I have an object that I want to clone, so I look up the copy constructor for its type and then want to invoke it. Here's what I have: public Object clone(Object toClone) { MethodBase copyConstructor = type.GetConstructor( new Type[] { toClone.GetType() }); return method.Invoke(toClone, new object[] { toClone }); //<-- doesn't work } I call the above method like so: List list = new List(new int[] { 0, 1, 2 }); List clone = (List) clone(list); Now, notice the invoke method I'm using is MethodBase's invoke. ConstructorInfo provides an invoke method that does work if invoked like this: return ((ConstructorInfo) method).Invoke(new object[] { toClone }); However, I want to use MethodBase's method, because in reality instead of looking up the copy constructor every time I will store it in a dictionary, and the dictionary contains both methods and constructors, so it's a Dictionary<MethodBase>, not Dictionary<ConstructorInfo>. I could of course cast to ConstructorInfo as I do above, but I'd rather avoid the casting and use the MethodBase method directly. I just can't figure out the right parameters. Any help? Thanks so much.

    Read the article

  • Getting Argument Names In Ruby Reflection

    - by Joe Soul-bringer
    I would like to do some fairly heavy-duty reflection in the Ruby programming language. I would like to create a function which would return the names of the arguments of various calling functions higher up the call stack (just one higher would be enough but why stop there?). I could use Kernel.caller go to the file and parse the argument list but that would be ugly and unreliable. The function that I would like would work in the following way: module A def method1( tuti, fruity) foo end def method2(bim, bam, boom) foo end def foo print caller_args[1].join(",") #the "1" mean one step up the call stack end end A.method1 #prints "tuti,fruity" A.method2 #prints "bim, bam, boom" I would not mind using ParseTree or some similar tool for this task but looking at Parsetree, it is not obvious how to use it for this purpose. Creating a C extension like this is another possibility but it would be nice if someone had already done it for me. Edit2: I can see that I'll probably need some kind of C extension. I suppose that means my question is what combination of C extension would work most easily. I don't think caller+ParseTree would be enough by themselves. As far as why I would like to do this goes, rather than saying "automatic debugging", perhaps I should say that I would like to use this functionality to do automatic checking of the calling and return conditions of functions. Say def add x, y check_positive return x + y end Where check_positive would throw an exception if x and y weren't positive (obviously, there would be more to it than that but hopefully this gives enough motivation)

    Read the article

  • Reflection: cast an object to subclass without use instaceof

    - by Fabrizio
    I have this simple interface/class: public abstract class Message { } public class Message1 extends Message{ } public class Message2 extends Message{ } And an utility class: public class Utility { public void handler(Message m){ System.out.println("Interface: Message"); } public void handler(Message1 m){ System.out.println("Class: Message1"); } public void handler(Message2 m){ System.out.println("Class: Message2"); } } Now, the main class: public static void main(String[] args) { Utility p=new Utility(); Message1 m1=new Message1(); p.handler(m1); Message m=(Message) m1; p.handler(m); } The output is Class: Message1 Interface: Message I would that p.handler(m) call the method p.handler(m:Message1) I don't want use the "manual" command instanceof because I have many cases: if(m instance of Message1) p.handler((Message1)m) else if (m instanceof Message2) p.handler((Message2)m) ... If I call m.getClass() I obtain "mypackage.Message1", so the subclass and not the superclass. I try with this code (use reflection): p.handler(m.getClass().cast(m)); But the output is Interface: Message So, this is my problem. I would do a runtime cast of superclass object to subclassobject without use the "code command" istanceof. I would a right command like this: p.handler((m.getclass)m); How can I obtain it? It's possible? Thank in advance. Fabrizio

    Read the article

  • Unit testing that an event is raised in C#, using reflection

    - by Thomas
    I want to test that setting a certain property (or more generally, executing some code) raises a certain event on my object. In that respect my problem is similar to http://stackoverflow.com/questions/248989/unit-testing-that-an-event-is-raised-in-c, but I need a lot of these tests and I hate boilerplate. So I'm looking for a more general solution, using reflection. Ideally, I would like to do something like this: [TestMethod] public void TestWidth() { MyClass myObject = new MyClass(); AssertRaisesEvent(() => { myObject.Width = 42; }, myObject, "WidthChanged"); } For the implementation of the AssertRaisesEvent, I've come this far: private void AssertRaisesEvent(Action action, object obj, string eventName) { EventInfo eventInfo = obj.GetType().GetEvent(eventName); int raisedCount = 0; Action incrementer = () => { ++raisedCount; }; Delegate handler = /* what goes here? */; eventInfo.AddEventHandler(obj, handler); action.Invoke(); eventInfo.RemoveEventHandler(obj, handler); Assert.AreEqual(1, raisedCount); } As you can see, my problem lies in creating a Delegate of the appropriate type for this event. The delegate should do nothing except invoke incrementer. Because of all the syntactic syrup in C#, my notion of how delegates and events really work is a bit hazy. How to do this?

    Read the article

  • .net runtime type casting when using reflection

    - by Mike
    I have need to cast a generic list of a concrete type to a generic list of an interface that the concrete types implement. This interface list is a property on an object and I am assigning the value using reflection. I only know the value at runtime. Below is a simple code example of what I am trying to accomplish: public void EmployeeTest() { IList<Employee> initialStaff = new List<Employee> { new Employee("John Smith"), new Employee("Jane Doe") }; Company testCompany = new Company("Acme Inc"); //testCompany.Staff = initialStaff; PropertyInfo staffProperty = testCompany.GetType().GetProperty("Staff"); staffProperty.SetValue(testCompany, (staffProperty.PropertyType)initialStaff, null); } Classes are defined like so: public class Company { private string _name; public string Name { get { return _name; } set { _name = value; } } private IList<IEmployee> _staff; public IList<IEmployee> Staff { get { return _staff; } set { _staff = value; } } public Company(string name) { _name = name; } } public class Employee : IEmployee { private string _name; public string Name { get { return _name; } set { _name = value; } } public Employee(string name) { _name = name; } } public interface IEmployee { string Name { get; set; } } Any thoughts? I am using .NET 4.0. Would the new covariant or contravariant features help? Thanks in advance.

    Read the article

  • Dynamically class creating by using Java Reflection, java.lang.ClassNotFoundException

    - by rubby
    Hi all; i want to use reflection in java, i want to do that third class will read the name of the class as String from console. Upon reading the name of the class, it will automatically and dynamically (!) generate that class and call its writeout method. If that class is not read from input, it will not be initialized. I wrote that codes but i am always taking to "java.lang.Class.Not.Found.Exception", and i don't know how i can fix it. Can anyone help me? class class3 { public Object dynamicsinif(String className, String fieldName, String value) throws Exception { Class cls = Class.forName(className,true,null); Object obj = cls.newInstance(); Field fld = cls.getField(fieldName); fld.set(obj, value); return obj; } public void writeout3() { System.out.println("class3"); } } public class Main { public static void main(String[] args) throws Exception { System.out.println("enter the class name : "); BufferedReader reader= new BufferedReader(new InputStreamReader(System.in)); String line=reader.readLine(); String x="Text1"; try{ class3 trycls=new class3(); Object gelen=trycls.dynamicsinif(line, x, "rubby"); Class yeni=(Class)gelen; System.out.println(yeni); }catch(ClassNotFoundException ex){ System.out.print(ex.toString()); } } }

    Read the article

  • dll's loaded through reflection

    - by Seattle Leonard
    Ok, I got a strange one here and I want to know if any of you have ever run accross anything like it. So I've got this web app that loads up a bunch of dll's through reflection. Basically it looks for Types that are derived from certain abstract types and adds them to the list of things it can make. Here's the weird part. While developing there is never a problem. When installing it, there is never a problem to start with. Then, at a seemingly random time, the application breaks while trying to find all the types. I've had 2 sites sitting side by side and one worked while the other did not, and they were configured exactly(and I mean exactly) the same. IISRESET's never helped, but this did: I simply moved all the dll's out of the bin directory then moved them back. That's right I just moved them out of the bin directory then put them right back where they came from and everything worked fine. Any ideas?

    Read the article

  • Using reflection to find all linq2sql tables and ensure they match the database

    - by Jake Stevenson
    I'm trying to use reflection to automatically test that all my linq2sql entities match the test database. I thought I'd do this by getting all the classes that inherit from DataContext from my assembly: var contexttypes = Assembly.GetAssembly(typeof (BaseRepository<,>)).GetTypes().Where( t => t.IsSubclassOf(typeof(DataContext))); foreach (var contexttype in contexttypes) { var context = Activator.CreateInstance(contexttype); var tableProperties = type.GetProperties().Where(t=> t.PropertyType.Name == typeof(ITable<>).Name); foreach (var propertyInfo in tableProperties) { var table = (propertyInfo.GetValue(context, null)); } } So far so good, this loops through each ITable< in each datacontext in the project. If I debug the code, "table" is properly instantiated, and if I expand the results view in the debugger I can see actual data. BUT, I can't figure out how to get my code to actually query that table. I'd really like to just be able to do table.FirstOrDefault() to get the top row out of each table and make sure the SQL fetch doesn't fail. But I cant cast that table to be anything I can query. Any suggestions on how I can make this queryable? Just the ability to call .Count() would be enough for me to ensure the entities don't have anything that doesn't match the table columns.

    Read the article

  • Java reflection appropriateness

    - by jsn
    This may be a fairly subjective question, but maybe not. My application contains a bunch of forms that are displayed to the user at different times. Each form is a class of its own. Typically the user clicks a button, which launches a new form. I have a convenience function that builds these buttons, you call it like this: buildButton( "button text", new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { showForm( new TasksForm( args... ) ); } } ); I do this dozens of times, and it's really cumbersome having to make a SelectionAdapter every time. Really all I need for the button to know is what class to instantiate when it's clicked and what arguments to give the constructor, so I built a function that I call like this instead: buildButton( "button text", TasksForm.class, args... ); Where args is an arbitrary list of objects that you could use to instantiate TasksForm normally. It uses reflection to get a constructor from the class, match the argument list, and build an instance when it needs to. Most of the time I don't have to pass any arguments to the constructor at all. The downside is obviously that if I'm passing a bad set of arguments, it can't detect that at compilation time, so if it fails, a dialog is displayed at runtime. But it won't normally fail, and it'll be easy to debug if it does. I think this is much cleaner because I come from languages where the use of function and class literals is pretty common. But if you're a normal Java programmer, would seeing this freak you out, or would you appreciate not having to scan a zillion SelectionAdapters?

    Read the article

  • Working with libpath with java reflection.

    - by C. Ross
    I'm dynamically loading a class and calling a method on it. This class does JNI. When I call the class, java attempts to load the library. This causes an error because the library is not on the libpath. I'm calling from instead a jar so I can't easily change the libpath (especially since the library is not in the same directory or a sub directory of the jar). I do know the path of the library, but how can I load it before I load the class. Current code: public Class<?> loadClass(String name) throws ClassNotFoundException { if(!CLASS_NAME.equals(name)) return super.loadClass(name); try { URL myUrl = new URL(classFileUrl); URLConnection connection = myUrl.openConnection(); InputStream input = connection.getInputStream(); byte[] classData = readConnectionToArray(input); return defineClass(CLASS_NAME, classData, 0, classData.length); } catch (MalformedURLException e) { throw new UndeclaredThrowableException(e); } catch (IOException e) { throw new UndeclaredThrowableException(e); } } Exception: Can't find library libvcommon.so java.lang.UnsatisfiedLinkError: vcommon (A file or directory in the path name does not exist.) at java.lang.ClassLoader.loadLibraryWithPath(ClassLoader.java:998) at java.lang.ClassLoader.loadLibraryWithClassLoader(ClassLoader.java:962) at java.lang.System.loadLibrary(System.java:465) at vcommon.(vcommon.java:103) at java.lang.J9VMInternals.initializeImpl(Native Method) at java.lang.J9VMInternals.initialize(J9VMInternals.java:200) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37) at java.lang.reflect.Method.invoke(Method.java:599) at com.fortune500.fin.v.vunit.reflection.ReflectionvProcessor.calculateV(ReflectionvProcessor.java:36) at com.fortune500.fin.v.vunit.UTLTestCase.execute(UTLTestCase.java:42) at com.fortune500.fin.v.vunit.TestSuite.execute(TestSuite.java:15) at com.fortune500.fin.v.vunit.batch.Testvendor.execute(Testvendor.java:101) at com.fortune500.fin.v.vunit.batch.Testvendor.main(Testvendor.java:58) Related: Dynamic loading a class in java with a different package name

    Read the article

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