Let me give an idea of what I wish to do: I have a structure or class called student, which contains variables like
int roll_no
and
int reg_no
If the user wishes to add a new variable like char name at run time how can it be done?
Based on the word "Structure" and the variable declarations, I'm going to guess this question is about some flavor of C. How exactly to do this will depend on the language, but as a general rule, if the language is compiled (e.g. C/C++, Java), this is not possible. If the language is interpreted (e.g. Python), this might sort of be possible, like this:
class MyObj:
message = "Hi there"
a = MyObj() # Creating a new instance variable
a.name = "Bill" # Adding a new attribute
Here we've added the name attribute to the a object only, and not the entire class. I'm not sure how you're go about that for the whole class.
But really, the answer to your question is "Don't". You should think about your program and the objects you're using enough to know what fields you will and won't need. If you'll want to have a name field at some point in your program, put it in the class declaration. If you don't want it to have a value on object creation, use a sensible default like null.
Edit
Based on your comments, there are a couple of ways to approach this. I'm still not entirely clear on what you want, but I think one of these cases should cover it. Of the languages I know, Python is the most flexible at runtime:
Python
In Python, a class is just another kind of object. Class variables (check out this question too) belong to the class itself, and are inherited by any instances you create:
class MyObj:
a = 2 # A class variable
b = "a string" # Another one
ObjInstance = MyObj() # Creating an instance of this class
print ObjInstance.a # Output: "2"
ObjInstance.a = 3 # You can access and change the value of class variables *for this instance*
print MyObj.a, ObjInstance.a # Outputs "2 3". We've changed the value of a for the instance
MyObj.c = (3,4) # You can add a new class variable at runtime
# Any instance objects inherit the new variable, whether they already exist or not.
print MyObj.c, ObjInstance.c # Outputs "(3, 4) (3, 4)"
You can use this to add attributes to every instance of your class, but they will all have the same value until you change them. If you want to add an attribute to just one instance, you can do this:
ObjInstance.d = "I belong to ObjInstance!"
print ObjInstance.d # Output: "I belong to ObjInstance!"
print MyObj.d # Throws "AttributeError: class MyObj has no attribute 'd'"
One drawback to using Python is that it can be kinda slow. If you want to use a compiled language it will be slightly more complicated, and it will be harder to get the same functionality that I mentioned above. However, I think it's doable. Here's how I would do it in Java. The implementation in C/C++ will be somewhat different.
Java
Java's class attributes (and methods) are called (and declared) static:
class MyObj {
public static int a = 2;
public static String b = "a string";
}
static variables are normally accessed through the class name, as in Python. You can get at them through an instance, but I believe that generates a warning:
System.out.println(MyObj.a); //Outputs "2"
MyObj ObjInst = new MyObj();
System.out.println(ObjInst.a); //Outputs "2" with a warning. Probably.
You can't add attributes to a Java object at runtime:
ObjInst.c = "This will break"; // Throws some exception or other
However, you can have a HashMap attribute, static or not, which you can add entries to at runtime that act like attributes. (This is exactly what Python does, behind the scenes.) For example:
class MyObj {
private HashMap<String, Object> att = new HashMap<String, Object>();
public void setAttribute(String name, Object value) {
att.put(name, value);
}
public Object getAttribute(String name) {
return att.get(name);
}
}
And then you can do things like:
ObjInst.setAttribute("name", "Joe");
System.out.println(ObjInst.getAttribute("name"));
Notice that I did not declare att static above, so in this case each instance of the MyObj class has this attribute, but the class itself does not. If I had declared it static, the class itself would have one copy of this hash. If you want to get really fancy, you can combine the two cases:
class MyObj {
private static HashMap<String, Object> classAtt = new HashMap<String, Object>();
private HashMap<String, Object> instAtt = new HashMap<String, Object>();
public static void setClassAttribute(String name, Object value) {
classAtt.put(name, value);
}
public void setInstAttribute(String name, Object value) {
instAtt.put(name, value);
}
public Object getAttribute(String name) {
// Check if this instance has the attribute first
if (this.instAtt.containsKey(name) {
return instAtt.get(name);
}
// Get the class value if not
else {
return classAtt.get(name);
}
}
}
There are a few details I've left out, like handling the case of the HashMaps not having the value you're asking for, but you can figure out what to do there. As one last note, you can do in Python exactly what I did here in Java with a dict, and that might be a good idea if the attribute names will be strings. You can add an attribute as a string in Python but it's kind of hard; look at the documentation on reflection for more info.
Good luck!
Related
As title, is there any way to iterate or display Apache velocity template attributes?
for example, I have following code :
<code>
${ctx.messages.headerMessage}
</code>
And I want to know how many other attributes the variable ${ctx} has
It's only possible to discover and to loop on an object properties (that is, the ones with getters and/or setters) if you can add a new tool to your Velocity context. If you can't, you're rather stuck.
There are several ways to do this, I illustrate below how to do this with commons-beanutils.
First, add Apache commons-beanutils in your class path, and add it to your Velocity context from Java:
import org.apache.commons.beanutils.PropertyUtils;
...
context.put("beans", new PropertyUtils());
...
One remark: if you do not have access to the Java part, but if by chance commons-beanutils is already in the classpath, there is one hakish way of having access to it: #set($beans = $foo.class.forName('org.apache.commons.beanutils.PropertyUtils').newInstance()).
Then, let's say that I have the following object:
class Foo
{
public boolean isSomething() { return true; }
public String getName() { return "Nestor"; }
}
which is present in my context under $foo. Using your newly $beans properties introspector, you can do:
#set ($properties = $beans.getPropertyDescriptors($foo.class))
#foreach ($property in $properties)
$property.name ($property.propertyType) = $property.readMethod.invoke($foo)
#end
This will produce:
bar (boolean) = true
class (class java.lang.Class) = class Foo
name (class java.lang.String) = Robert
(you'll need to filter out the class property, of course)
One last remark, though. Templates are for coding the View layer of an MVC application, and doing such a generic introspection of objects in them is rather inadequate in the view layer. You're far better of moving all this introspection code on the Java side.
In my understanding, a static member belongs to the class rather than to a specific instance of that class. It can be useful if either all instances share this specific characteristic with the exact same value, or if I do not want to create any instances of the class at all.
So, if I have a class Car, and all my cars will always have exactly 4 wheels, I could store the number of wheels as a static member of the class Car rather than as a instance variable of a myCar class instance.
But why should it be not possible in Haxe to access the static variable from a class instance? Doesn't make any sense to me.
class Car
{
public static var noOfWheels:Int = 4;
public static function getNoOfWheels():Int
{
return Car.noOfWheels;
}
}
class Main
{
static function main()
{
myCar = new Car();
trace (myCar.noOfWheels);
trace (myCar.getNoOfWheels());
trace (Type.getClass(myCar).noOfWheels);
}
}
Neither of those traces lead to the desired result. The first and second trace result in an error of the type:
Cannot access static field XY from a class instance
while the third leads to:
Class <Car> has no field noOfWheels
Edit for clarification:
I have several child classes of the Car class, inheriting all its properties. In some cases, like the class ItalianVan, I declare the static variable noOfWheels again, thus overshadowing the original Car.noOfWheels.
class ItalianVan extends Car
{
public static var noOfWheels:Int = 3;
}
Now, if I have an arbitrary car instance, I would like to know how many wheels it has. If I access the Car.noOfWheels, the answer would always be 4 wheels, even if that special car actually was a three-wheeled italian van.
Maybe the answer is: Don't use static variables for stuff like that!
But it isn't obvious to me why.
Seems unnecessary to make noOfWheels an instance variable, if all members of that class have the same number of wheels.
I've never used Haxe but I can see that you are accessing to the myCar variable.
Try this:
trace (Car.noOfWheels);
trace (Car.getNoOfWheels());
When you want to access to a static variable you should use the class name.
To access a static variable from an instance maybe you can add a non static method that returns the result of the static call.
I encountered the situation mentioned in the topic now more than once and now I want to ask in here for
other opinions, hints, explanations, why someone should/would/ do things like this:
There is an object of class A, which implements the interface I_1o
This object has a static member, a collection, typed by interface I_1.
The class A has an interface-implemented method, which is called get_instance ( key-params ).
It looks inside the collection for a specified object fitting the key params and returns the
relevant object.
Is there a name for this (design pattern, whatever), a reason, a "best practice" explanation, why this seems to be a singleton but on the other hand it is not, just recursive object holding?
If no one understands, what I mean, just let me know, I will try to clarify it then.
This sounds an awful lot like an Object Pool design pattern. Documentation here.
This looks something like this:
public class Pool
{
private static int MAX_ELEMS = 10;
private static List<Object> instances;
private static void initialise()
{
if(instances == null) {
instances = new ArrayList<Object>();
// Initialise all the objects in the list.
}
}
public static Object getInstance(String key)
{
for(Object instance : instances) {
if(instance.equals(key)) { // Just an example
return instance;
}
}
}
}
The reason for this design pattern is to avoid the expensive re-instanciation of objects. If you have a load of, for example, Server connection objects, and you want to limit the amount of connections to the server, then you implement a pattern like this. It will mean that no more than MAX_ELEMS objects exist at one time, and it also means that they are not created during use of the program; they are built during some loading period in the program.
This looks like a Registry or IdentityMap.
I a new at OO programming and trying to clear up a few things.
When you instatiate a class and create an object, Ive seen the following:
class Program
{
static void Main(string[] args)
{
MyClassA a = new MyClassA();
MyClassA b = a;
MyClassA c = b;
c.DoSomething();
Console.ReadLine();
}
}
public class MyClassA
{
public void DoSomething()
{
Console.WriteLine("I am from Class A");
}
}
This may be a bad example, but the question I am trying to get answered is:
Why is pointing one object reference to another important or why\where is it used? Why not use the object you created in the first place?
This is more Java than generically "object-oriented" -- C++ would be completely different (if you need to "refer" to objects, and change to what object a certain variable "refers" to, you need to use explicit pointers -- references in C++ cannot be "reseated").
Anyway, unconditionally creating synonyms like in your example has no point nor purpose. Much more typical uses would be, for example,
MyClass a = ...whatever...;
MyClass b = ...whatever else...;
MyClass c;
if(something()) {
c = a;
} else {
c = b;
}
c.dosomething();
c.blahblah();
c.andmore();
i.e., having a "synonym" that can refer to one object, or to another one, depending on circumstances, so that following operations can always be coded as being "on the synonym" and they'll be on the "right" object either way (alternatives such as duplicating the whole blocks of "following operations" are, at the very least, very bad and repetitious style, and, e.g. when some of the "following operations" are in other methods and the "synonym" is an instance variable rather than a local variable, can be extremely hard to code, too).
This is just the simplest example, of course. But, do you really need other, more complicated ones?-)
Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.