I developed an application named as AAA in that application im referring an assembly named as BBB. At certain condition im loading that BBB assemby into my application using Assembly.LoadFromFile() function. Now i need to access certain object instances of AAA in BBB assembly at run time.Is it possible to accomplish this task?
Thanks in Advance .
Are you trying to create new instances of your objects? If so, this should work:
Assembly ass = Assembly.LoadFrom("BBB.dll");
Object myObject = ass.CreateInstance("BBB.MyObject");
Note this assumes that your object has a default constructor - if you need to pass parameters into the constructor, you can do something like this (assuming a constructor which takes a string as its argument):
Assembly ass = Assembly.LoadFrom("BBB.dll");
Type t= ass.GetType("MyObject");
ConstructorInfo c = t.GetConstructor(new Type[]{typeof(string)});
Object myObject2 = c.Invoke(new object[] { "myParam" }
Let AAA hand a reference to the object to some variable in BBB after it has loaded.
To access object ooo from BBB, you should provide BBB with a (possibly indirect) reference to ooo. AAA may use reflection to discover the appropriate entry point for BBB and then provide it with ooo.
Related
In Eiffel Studio, I have been trying to access the fields of an object of a class I have defined from another class. However, it keeps giving errors that I am not able to understand and solve. The following is a snippet of example code:
Class where object is being created:
class
TEST1
feature
object: TEST2
-- object of type TEST2
function(val: INTEGER)
-- Assign
do
object.value:=val
end
end
Class whose object is being created:
class
TEST2
feature
value: INTEGER
end
The error messages are as follows:
Error code: VBAC(2)
Error: target of assigner call has no associated assigner command.
What to do: add an assigner mark to the declaration of the target feature or use a dot form of a call.
Class: TEST1
Feature: function
Line: 10
do
-> object.value:=val
end
and
Error code: VEVI
Error: variable is not properly set.
What to do: ensure the variable is properly set by the correspondig setter instruction.
Class: TEST1
Source class: ANY
Feature: default_create
Attribute(s): object
Line: 331
do
-> end
It seems that there is some problem with the assignment statement. However, I haven't been able to understand what is wrong.
The classes have been defined in different files under the same cluster of the same project. I am new to Eiffel, so I don't know if this could be the problem.
Thank you.
In Eiffel, every attributes are considerate as Read-Only. This remove the need to create getters like you do in other languages like Java. To assign a value to an attribute using the ":=" syntaxe, you will need an assigner. Here an example:
class
TEST2
feature
value:INTEGER assign set_value
set_value(a_value:INTEGER)
do
value := a_value
end
end
Then, you will be able to use the line:
object.value:=val
For the second error, by default, EiffelStudio is what we call Void Safe. This is a mecanism that ensure that an attribute that is not considerated as "detachable" will never be Void (similar to NULL in other languages). By default, every class have the default constructor called "default_create" and this constructor does not do anything. What you have to do, is creating you own constructor in the {TEST1} class that instanciate every attribute inside it. Here is an example:
class
TEST1
create
make
feature
make
do
create object
end
object: TEST2
-- object of type TEST2
function(val: INTEGER)
-- Assign
do
object.value:=val
end
end
In the preceding example, I created a method call make, specify that the method is the constructor and in this method, I make sure that the object attribute is correctly instanciate.
I am developing a C++ application where I need to create X amount of classes. Let's say: class AAA, BBB and CCC. Each class corresponds to one type of object which I would need to process.
On the other hand, I have an input file of CVS type. One example of that input file looks like this one:
AAA,3432443,433434,11111,45678
AAA,8778776,786698,22222,86881
BBB,4452332,112234,34543,87734
So, I need to parse that input file, and according to the first element of the line (AAA, BBB, CCC), I need to create the corresponding object which will store the other values found in the line.
BUT, I cannot "embedded" in the application the possible classes (AAA, BBB, CCC) in order to use a chain of conditionals, like:
if (token == "AAA") then AAA aaa = new AAA (params);
Instead:
The application must remain independent of the existing classes, in such way that in the future we can add classes DDD, EEE, ... ZZZ, without modifying the module which creates the objects (in case of using conditionals, I should add, for instance: if (token == "DDD") then DDD ddd = new DDD(params). This is forbidden.
I have created a configuration file which provides the possible class types in the current execution:
AAA
BBB
CCC
...
In this way, I can loop over this class types and compare against the ones read from the first element in the input file lines. But I am stuck in the problem of how I can create an object of an unknown class. Something like this:
retrieved_type_from_input_file object = new retrieved_type_from_input_file(params);
where "retrieved_type_from_input_file" is a variable which contains the effective type of class I should create: AAA ... ZZZ
I am thinking in generic programming. Something like:
T object = new T(params);
But even though I can code this inside a class; in the implementation I need the real name of the class.
I am thinking also in the implementation of some kind of Factory pattern, creating some kind of abstract parent class ("Thing") from which everyone would be inheriting ( class AAA: public Thing). But all the models which I find, make explicit reference to the name of the class, in some place of the code, at the moment of creating the object.
Any help please?
Thanks a lot in advance!!
i am guessing, you are in need of code generator :
Step 1. Write a program that generates classes in .h, .cpp files based on your configuration file.
you can alse create/declare objects of the classes in this step
Step 2. Make use of generated classes , to build an exe file.
This is my rough idea, and looking for other possibilites from others.
I want to split up a large class by using mixins.
I am using this mixin code from the Little Book
#include: (obj) ->
for key, value of obj when key not in moduleKeywords
# Assign properties to the prototype
#::[key] = value
obj.included?.apply(#)
this
class FooMixin
b: => #something = 2
class Foo extends Module
#include FooMixin
a: => #something = 1
Problem is that # in FooMixin is FooMixin. I want it to be Foo instead.
I have tried adding the line _.bind(#::[key], #) at the end of #include() but it doesn't help. Any suggestions?
Okay, few things I was doing wrong.
1.
#include from the Little Book takes an object not a class. To get it to work with classes you need to write #include FooMixin::. However, I have since begun using objects instead.
2.
When using an object instead of a class, the fat arrow adds a line inside the CoffeeScript wrapper right at the top which reads _this = this. All methods are bound to the global context which is not what we want. To fix we must convert fat arrows to thin arrows, and bind each function to our Foo instance. Using Underscore I added this to the constructor of Foo:
constructor: ->
for fname in _.functions FooMixin
#[fname] = _.bind #[fname], #
super
I tried _.bindAll #, _.functions FooMixin but it gave me an error saying something like At Function.bind, could not run bind of undefined. Weird error, seeing as the code above is pretty much identical to the _.bindAll method.
So now I can split my classes up for better readability and code sharing.
UPDATE: The problem with _.bindAll is that it takes a splat not an array. Fix is to use _.bindAll #, _.functions(FooMixin)....
UPDATE: Found a better solution.
Same as original post. Use classes for mixins.
Use #include FooMixin:: or change #include to operate on a prototype instead of properties.
In the Foo constructor write FooMixin.call # which binds the methods correctly.
This works well and is nice and clean.
The only potential issue is that mixins will be overridden by existing properties. The only way to get around this that I can see is to do something like:
after = ->
_.extend Foo, FooMixin::
class Foo
# define...
after()
Or pass the extend method to _.defer but this is so hacky and probably won't work.
I'm writing a metaclass to do some cool stuff, and part of its processing is to check that certain attributes exist when the class is created. Some of these are mutable, and would normally be set in __init__, but since __init__ isn't run until the instance is created the metaclass won't know that the attribute will be created, and raises an error. I could do something like:
class Test(meta=Meta):
mutable = None
def __init__(self):
self.mutable = list()
But this approach has several problems:
it forces the creation of a class attribute that is not the same type as the instance attribute
__init__ still has to shadow the class attribute, and Meta is not checking that
if __init__ doesn't shadow the class attribute I'll still get errors down the line (such as AttributeError: 'NoneType' object has no attribute 'append'), and trying to avoid such errors is part of the function of Meta
and last but not least, it violates DRY.
What I need is a way to have something like:
class Test(metaclass=Meta):
mutable = list()
But each instance will end up with its own copy of mutable.
The design goals are:
the attribute must exist in the class (type doesn't matter -- it is not checked)
at some point before the attribute is first used a copy of the attribute is placed in the instance
A desired sample run:
t1 = Test()
t2 = Test()
t1.mutable.append('one')
t2.mutable.append('two')
t1.mutable # prints ['one']
t2.mutable # prints ['two']
Any ideas on how this can be accomplished?
There are at least three ways to do this:
Have the metaclass check all the attributes, and if they are one of the mutables (list, dict, set, etc.) replace the attribute with a descriptor that will activate on first access and update the instance with a fresh copy of the mutable.
Provide the descriptor from (1) as a decorator to be used when writing the class.
Have the metaclass add its own __init__ method to the class which when run:
calls the original __init__
then checks that the required attributes are present
Downsides (by method):
Extra effort is required if the class has a mutable attribute that should be shared across all instances.
The attribute in the class becomes a function in the class (possible mind-warp ;)
Move the point of error to class instantiation instead of class definition.
I prefer (2) is it gives complete control to the class author, simplifies those cases where the class-level mutable attribute should be shared amongst all the instances, and keeps the error at class definition.
Here's the decorator-descriptor:
class ReplaceMutable:
def __init__(self, func):
self.func = func
def __call__(self):
return self
def __get__(self, instance, owner):
if instance is None:
return self
result = self.func()
setattr(instance, self.func.__name__, result)
return result
and the test class:
class Test:
#ReplaceMutable
def mutable():
return list()
How it works:
Just like property, ReplaceMutable is a descriptor object with the same name as the attribute it is replacing. Unlike property, it does not define __set__ nor __delete__, so when code tries to rebind the name (mutable in the test above) in the instance Python will allow it to do so. This is the same idea behind caching descriptors.
ReplaceMutable is decorating a function (with the name of the desired attribute) that simply returns whatever the instance level attribute should be initialized with (an empty list in the example above). So the first time the attribute is looked up on an instance it will not be found in the instance dictionary and Python will activate the descriptor; the descriptor then calls the function to retrieve the initial object/data/whatever, stores it in the instance, and then returns it. The next time that attribute is accessed on that instance it will be in the instance dictionary, and that is what will be used.
Sample code:
t1 = Test()
t2 = Test()
t1.mutable.append('one')
t2.mutable.append('two')
print(t1.mutable)
print(t2.mutable)
I've seen this recently and now I can't find it …
How do you set the class of an object to something else?
--Update: Well, in Pharo! Like:
d:=Object new. d setClass: Dictionary.
Only that it isn't actually setClass. How can you modify the class pointer of an object?
There is #primitiveChangeClassTo:.
It requires that both original and target class have the same class layout. For some strange reason it expects an instance of the target class as parameter, which is however not used.
So you would do
d := Object new.
d primitiveChangeClassTo: Dictionary new.
however this fails, since dictionaries have two instance variables but plain objects have none.
If you are into meta-programming, you might also be interesting in using any object as a class. I used that in Protalk to realize a prototype based language that works directly on top of Smalltalk.
The method #setClass: is used in some specific contexts and with different implementations (Check it with the Method Finder).
Object has some helpers to conver the current object in other sort of, as for example #asOrderedCollection, because this last permit the operation:
asOrderedCollection
"Answer an OrderedCollection with the receiver as its only element."
^ OrderedCollection with: self
HTH.
ok, then you can try something as:
d := Object new.
e := Dictionary new.
d become: e.
But, please, try #become: with caution, because in lot of situations it break the image.
Take a look at Class ClassBuilder. It creates the a new class, when you modify a class, and then switches the instances of the former to instances of the later. Therefor it should provide some method that does, what you ask for.