I am working on a module where I have to convert a set of logical representations and other data into Java source code.
I would like to be able to first convert them to an intermediary representation of Java elements (classes, methods, etc), and then convert this intermediary representation to an actual String/textfile.
for example, I would like to just be able to construct an element like this:
JavaClass myClass = new JavaClass("MyClass", "MyParent", new String[] {"MyInterface", "MySecondInterface"});
and then have the toString() method of myClass output something like:
class MyClass extends MyParent implements MyInterface, MySecondInterface { }
and so on and so forth for variables, methods, statements etc - preferably with formatting. The example is oversimplified just for the sake of demonstration - in reality I would prefer a representation that at least resembles an abstract syntax tree.
I have looked at the com.sun.org.apache.bcel.* package, but since it is meant for bytecode it does not help much here. Transformation frameworks (such as Recoder) also do not seem to be what I am looking for.
Can anyone recommend a framework I can use for this?
You could use a template engine like freemarker. Write a 'class' template and use freemarker to put in your data. Really simple to use. Freemarker support everything you need like interation, conditions, ...
You should look into Javassist. It has a really simple API for creating classes on the fly.
Related
I described my previous problem here:
Java - how can I loop methods with same name but different parameters
And I have question related to that.
Is given there example - a good example of using wrapper class?
class Wrapper{
Part param1;
File param2;
File param3;
}
class Validator{
void validate (Wrapper wrapper);
}
class ValidatorA extends Validate{
void validate (Wrapper wrapper){
//use wrapper.part...
}
}
class ValidatorC extends Validate{
void validate (Wrapper wrapper){
//use wrapper.file...
}
}
But it makes me wonder. Is wrapper correct name for it? Is is valid wrapper class? From what I read wrapper classes are used for primitives to use them as objects, shouldn't then it be named different? Or am I wrong?
I need it to be called same way, so I can loop over it so overloading is not the answer. Given class works fine - I just think if is it correct way to use wrapper name?
Wrapper is not good choice in this case. Usually wrapper is used to wrap some different things so they look alike even they are totally different. For example you may have some stream of data which comes from different sources - file, http connection, resources. All what you care is to read data from this source. So, you write wrapper which reads from any source and just deliver data.
Wrapper should not be mixed with common functionality. In example above all 3 sources could be treated as stream so natural solution would be use them all as streams. But even eventually inside wrapper they are used as streams they still require different treatment and actions to work with them. And wrapper takes care about it. You do not care what is wrapped wraps - you just use this wrapped thing in common way which wrapper provides.
In your example we have regular object which encapsulates some data and functionality. This is regular OOP approach. Calling it Wrapper only misguide users who may use this code later.
I am fairly new to using Python as a OOP. I am coming from a Java background. How would you write a javabean equivalent in python? Basically, I need a class that:
Implements serializable.
Has getters and setters -> private properties
dummy constructor
Any inputs? I am looking for a sample code!
You don't, because Python is not Java. Most likely you should just write a less trivial class, construct a namedtuple, pass a dictionary, or something like that. But to answer the question:
Neither serializable nor "implementing an interface" makes sense in Python (well, in some frameworks and advanced use cases it does, but not here). Serialization modules, such as pickle, work without implementing or inheriting anything special (you can customize the process in other ways, but you almost never need to).
You don't write getters and setters. You just use public attributes. Should you later require a nontrivial getter/setter, you can turn it into a property transparently.
There's no need for a dummy constructor, unless you want to create the attributes and set default values for them. But that's probably a bad idea (for a bean-ish class), as not assigning values to those attributes is most likely an error, and dubious even when it isn't. So just let Python catch those errors for you (it raises AttributeError when a non-existent attribute is accessed).
Well, I'd think that data classes would be similar to Java beans and that using them is actually a good idea, as it removes boiler plate.
You can serialize most object via the pickle module;
There are no such things as private attributes in Python (see also:
Does python have 'private' variables in classes?,
Actual implementation of private variables in python class);
Classes that do not define a constructor will use a default (according to the method resolution order).
Example for constructor 'chain':
>>> class A(object):
... def __init__(self):
... print("A")
...
...
>>> class B(A): pass # has no explicit contructor
...
>>> b = B()
A
>>>
And - as #delnan wrote - you might want to read: http://dirtsimple.org/2004/12/python-is-not-java.html -- Java and Python have quite different cultures, it takes some time to dive into (and appreciate) both.
Also, after writing some code, it might be helpful to compare it to common idioms, as listed here (I certainly learned a lot this way):
http://www.jeffknupp.com/blog/2012/10/04/writing-idiomatic-python/
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
http://python3porting.com/improving.html
Implements serializable.
Pick your favorite format, and write a function that will serialize it for you. JSON, Pickle, YAML, any work. Just decide!
Has getters and setters -> private properties
We don't do that here, those are attributes of bondage languages, we are all adults in this language.
dummy constructor
Again not something we really worry about as our constructors are a little bit smarter than other languages. So you can just define one __init__ and it can do all your initialization, if you must then write a factory or subclass it.
As pointed by miku:
Objects can be serialized by picke module, but there is not an interface to be implemented, Python is not Java.
There is no private attribute in python, usually people use bar (the underscore) to mean private attributes, but they can be accessed from external world. Getters and setters are waste of time of both CPU and programmers.
Nothing to add to miku answer.
about properties: Real world example about how to use property feature in python?
good text: http://dirtsimple.org/2004/12/python-is-not-java.html
I have two classes in my Java project that are not 'related' to each other (one inherits from Thread, and one is a custom object. However, they both need to use the same function, which takes two String arguments and does soem file writing stuff. Where do I best put this function? Code duplication is ugly, but I also wouldn't want to create a whole new class just for this one function.
I have the feeling I am missing a very obvious way to do this here, but I can't think of an easy way.
[a function], which takes two String arguments and does soem file writing stuff
As others have suggested, you can place that function in a separate class, which both your existing classes could then access. Others have suggested calling the class Utility or something similar. I recommend not naming the class in that manner. My objections are twofold.
One would expect that all the code in your program was useful. That is, it had utility, so such a name conveys no information about the class.
It might be argued that Utility is a suitable name because the class is utilized by others. But in that case the name describes how the class is used, not what it does. Classes should be named by what they do, rather than how they are used, because how they are used can change without what they do changing. Consider that Java has a string class, which can be used to hold a name, a description or a text fragment. The class does things with a "string of characters"; it might or might not be used for a name, so string was a good name for it, but name was not.
So I'd suggest a different name for that class. Something that describes the kind of manipulation it does to the file, or describes the format of the file.
Create a Utility class and put all common utility methods in it.
Sounds like an ideal candidate for a FileUtils class that only has static functions. Take a look at SwingUtilities to see what I'm talking about.
You could make the function static in just one of the classes and then reference the static method in the other, assuming there aren't variables being used that require the object to have been instantiated already.
Alternatively, create another class to store all your static methods like that.
To answer the first part of your question - To the best of my knowledge it is impossible to have a function standalone in java; ergo - the function must go into a class.
The second part is more fun - A utility class is a good idea. A better idea may be to expand on what KitsuneYMG wrote; Let your class take responsibility for it's own reading/writing. Then delegate the read/write operation to the utility class. This allows your read/write to be manipulated independently of the rest of the file operations.
Just my 2c (+:
I would like to create a class in Java based on the fields defined in my XML config file:
For example: if the XML file contains (the syntax has been maligned for posting):
<property name="agent_host"></property>
<property name="subsystem"></property>
then internally it will create a class Event such as Event(String agentHost, String subSystem) that the client can instantiate. Note: the client always knows that this class will be called "Event" but does not know how many "mandatory parameters" it needs to pass.
On the other hand if I have a XML file with:
<property name="agent_host"></property>
then it will create Event(String eventHost) that the client can use for instantiation.
Yes, you could use reflection, but what comes to my mind is working with a class that you could add property.
Imagine a class that has one encapsulated HashMap using a String as a key (for the attribute name) and the value of the attribute so you could read the XML file and for evey property add the attribute to the class like.
For this line:
<property name="subsystem" type="String">value123</property>
GenericClass c = new GenericClass();
c.addAttribute("subsystem", new String("value123"));
//and you could implement a get and set methods like this:
public String getAttributeValue(String attributeName)
{
return internalHashMap.get(attributeName).toString();
}
Using this you could also implement a setAttributeValue
will be quite simple I think
If you really interested in creating a class dynamically, try Byte code Enhancement libraries like BCEL from Apache.
This isn't really a class you want, it's data. Why not use a hashmap? I really dislike "Bean" style classes--they encourage bad coding (there is no place in a generated class to put actual code, so everything ends up being manipulated by external code anyway).
You can just load a hashmap from your XML and inject it into a real object--that way you don't have to worry about actually passing a hash around, you are passing a real object with real business methods and real type safety--it just HAPPENS to use a hashmap internally to store data instead of member variables.
I've done a lot more than this, but at some point you realize Hibernate does everything you want for you.
I think the DynaBean from Commons-BeanUtils may be what you're looking for.
A DynaBean is a Java object that supports properties whose names and data types, as well as values, may be dynamically modified. To the maximum degree feasible, other components of the BeanUtils package will recognize such beans and treat them as standard JavaBeans for the purpose of retrieving and setting property values.
Out of curiosity, I'd like to know if any class exists in Java with a method that returns a copy of its data structure. I ask because in class the teacher said a method like this breaks privacy, but I think that getting a copy of the structure is useful if you want to rearrange the structure. I'd like an example. Thanks.
I'm not entirely sure what you mean by the "data structure" of a class, but assuming you mean the members it contains, what you're looking for is reflection.
Try this tutorial.
Maybe you are missing the point: If you build a class which encapsulates some kind of internal data then you should NOT add a method which returns the internal data structure, but only the data that is encapsulated.
(Which is kind of the idea of encapsulation)
There should not be any need to "rearrange" your internal representation from the outside - because it is supposed to be internal and thus transparent in its use. (Meaning: You should not even be able to say what kind of data structure is used)
If you serialize it, any object (that is serializable) will happily prints its internal structure to a binary stream. And yes, this breaks encapsulation.
And yes, no one stops you from going to change the binary output and read it in again to create an altered object.
NB: there are more strange issues regarding serialization. For example, when deserializing objects new objects are created without their constructor ever being called. Et cetera. Serialization of objects is the maybe least object-oriented thing one can do with objects.
You're mixing up some concepts here.
Classes really are "data structures + methods", so in general you'd need a class to represent your class. Hey, a nice custom-built one would be the class your data is already in. You may be thinking of a class as a collection of simple fields, but this is not always the case.
As others have mentioned, you can extract the data via reflection, e.g.
public Map<String,Object> fields() {
Map output=new hashMap<String,Object>();
for (Field f:getClass().getFields())
{
try{
output.put(f.getName(), f.get(this));
}
catch(... //IllegalArgument, IllegalAccess.. {... }
}
return output;
}
You can get into encapsulation issues here, in general the class should provide the data that you need to see from it, I tend to use things like this only for debugging.
I'm not sure what you mean by "rearrange the structure". The class generally represents the structure of the data. If there's a transformation you want to accomplish, it probably belongs in a class method, e.g. are you thinking of something like a co-ordinates class that can provide a transformed version of itself into polar co-ordinates?
A simple way to see the internal representation of an object is to serialise it using XStream. This will generate an XML representation of the class and its components (and so on).
Does this break encapsulation ? Yes - in the sense that you're able to inspect the internal structure of the class. You can take that XML, change it, and provided that it matches the .class structure that it came from, deserialise it back into a .class instance.