i am stucked on something : i have some .idl files that generates java classes from structs defined in those files like this :
struct MapServiceLayer{
string id;
string name;
string parentId;
OsTypes::StringSeq childrenIds;
};
However I need to have a JAVA class where one of it's Attributes needs to be of type Java.Object because when i will instantiate this class, its attribute could be of different type. So i tried this :
struct MapServiceFeatureAttribute{
OsTypes::ObjectSeq value;
};
and this :
struct MapServiceFeatureAttribute{
OsTypes::AnySeq value;
};
But none of those worked.
I also have heard about Unions but i am definitely not sure about how to use them. If someone knows how to get a Java.Object from idls this would be Great. If it's not possible maybe someone knows how to do with unions !
thanks in advance.
After some more deep research it seems that it is not possible to get a java.lang.object. However you can have a behavior that could do the trick using Any corba object :
After having generated your sources you will have a class with an attribute of type Any, this type allows you to store different types in it by using :
Any anyObj;
anyObj.insert_string(String s);
anyObj.insert_long(long l);
anyObj.insert_double(double d);
and you can obviously get the value and the chosen type by using :
String s1 = anyObj.extract_string(String s);
long l1 = anyObj.extract_long(long l);
double d1 = anyObj.extract_double(double d);
i gave the exemple for those 3 types but there is several more.
Related
When I try to use unknown types in the JvmModelInferrer it works for simple types, but does not work for generic types.
Example:
val unknownRef = typeRef('com.tmtron.ex.xtext2.usage.Unknown')
members += domainObject.toField('simpleField', unknownRef)
val listRef = typeRef(typeof(List), unknownRef)
members += domainObject.toField('list', listRef)
Note: the type com.tmtron.ex.xtext2.usage.Unknown does not exist in the target project.
The generator will produce this code:
private com.tmtron.ex.xtext2.usage.Unknown simpleField;
private /* List<com.tmtron.ex.xtext2.usage.Unknown> */Object list;
So the generated code for the simpleField is correct (or at least what I expected).
But for the generic list the code that I expected is commented out, and Object is used instead.
Why does this happen / how can I avoid this?
typeRef('java.util.List<com.tmtron.ex.xtext2.usage.Unknown>') should work as expected in this case.
For example in PHP:
<?php
$my_var = 1;
$my_var = [ "1" ]; // no problem
In Java, I tried to make a Class with a mixed argument:
class MyClass {
public String my_var;
}
MyClass c = new MyClass();
c.my_var = "ok";
c.my_var = 1; // error during compilation time
The reason I am asking that is because I am using jersey with json and I try to make a Feedback Class.
One argument in my Feedback class is the data to send back to the front-end in an Ajax manner. Sometimes data is a normal string:
`{ "data" : "hello world" }`
Sometimes it can be an array
`{ "data" : [ "hello", "world" ] }` or `{ "data" : [ { "id": 1 }, { "id": 2 }, ... ] }`
I am a real noobies when it comes to the Java language and libraries. The only solution I can think of now is to override the toString method for the objects involved in the Json encoding but "toString"'ing a List will give me something like that,
`{ "data" : "[ ...]" }` which is incorrect.
you can do this:
Object c = new Object();
c = new String("hi"); //valid
c = new Integer(1); //valid
And then to check what type of variable it is you can use instanceof
You can also make it an array or a list, and if you want to use toString on it generically to print out any object, you can make your own list class with an overridden toString method that prints it nicely, and use that class in your object
using objects with nice toString methods means that you won't have to use instanceof if all you want to do is get a string representation of the object
Java is a statically typed language; and "dynamics" are limited to things such as assigning sub class values to a super class variable, like:
Object o = "a string";
o = new Double(42.0);
So it looks like o can be both, String and Integer. But as said; that is because Object is a super type of both those classes.
This for example:
String s = "meow";
s = 42;
leads to a compiler error. What would work again would be s = Integer.toString(42) for example.
Similarly, you could do:
Object o = new int[5];
because in Java any reference type (including arrays) is a sub class of Object.
And just to be precise: the Java people think this is an advantage. Because it allows more checking at compile time - catching many errors that require you to write/run unit tests in those dynamic languages where a duck can meow like a cat and still be barking dog in the end.
Coming back to your question: from a Java point of view, an array is not the same as a string. And therefore you would not a low such a JSON representation. In other words: I would first try to change the JSON format.
If that is not possible, I would look into customized JSON de/serialization code - in order to have the framework decide which case is given and do the appropriate thing. Just as inspiration, you can have a look how this can be done with gson.
Currently you can't do that in Java yet, so you'd have to make an indirect workaround, but there are plans to implement typeless objects/variables in Java version 10 (currently at 8, almost moved to 9)
Think oops way,
Have an Interface like FeedBackResponse , Have different implementation classes for each of the cases, make them implement FeedBackResponse.
Each class will have different attributes.
Serialize the object using json library.
Ex,
FeedBackResponse response = getResponse("Some Service");
return jsonLib.serialize(response);
Factory
private FeedBackResponse getResponse(String attr){
// based on attr create ur object here.
}
Whilest learning Python 3 and converting some of my code from Java to Python 3.3 I came across a small problem I haven't been able to fix.
In Java I have this code (just dummy code to make it smaller):
public enum Mapping {
C11{public int getMapping(){ return 1;}},
C12{public int getMapping(){ return 2;}},
public abstract int getMapping();
}
String s = "C11";
System.out.println(Mapping.valueOf(s))
Works fine and prints the requisted '1'
Trying to do this in Python doesn't work that easy (yet). I tried to imitate an Enum with:
class Mapping:
C11=1
C12=2
s = 'C11'
print(Mapping.Mapping.(magic should happen here).s)
Unfortunately I have no idea how to convert a string to an attribute to be called like that (or something similar).
I need this because I have a HUGE list in the class Mapping and need to convert seemingly random words read from a text file to an integer mapping.
You are looking for getattr:
>>> getattr(Mapping, s)
1
From the documentation:
getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
Use getattr:
class Mapping:
C11=1
C12=2
print(getattr(Mapping, 'C11')) # prints 1
New to Java, and can't figure out what I hope to be a simple thing.
I keep "sections" in an array:
//Section.java
public static final String[] TOP = {
"Top News",
"http://www.mysite.com/RSS/myfeed.csp",
"top"
};
I'd like to do something like this:
Article a1 = new Article();
a1.["s_" + section[2]] = 1; //should resolve to a1.s_top = 1;
But it won't let me, as it doesn't know what "section" is. (I'm sure seasoned Java people will cringe at this attempt... but my searches have come up empty on how to do this)
Clarification:
My article mysqlite table has fields for the "section" of the article:
s_top
s_sports
...etc
When doing my import from an XML file, I'd like to set that field to a 1 if it's in that category. I could have switch statement:
//whatever the Java version of this is
switch(section[2]) {
case "top": a1.s_top = 1; break;
case "sports": a1.s_sports = 1; break;
//...
}
But I thought it'd be a lot easier to just write it as a single line:
a1["s_"+section[2]] = 1;
In Java, it's a pain to do what you want to do in the way that you're trying to do it.
If you don't want to use the switch/case statement, you could use reflection to pull up the member attribute you're trying to set:
Class articleClass = a1.getClass();
Field field = articleClass.getField("s_top");
field.set(a1, 1);
It'll work, but it may be slow and it's an atypical approach to this problem.
Alternately, you could store either a Map<String> or a Map<String,Boolean> inside of your Article class, and have a public function within Article called putSection(String section), and as you iterate, you would put the various section strings (or string/value mappings) into the map for each Article. So, instead of statically defining which sections may exist and giving each Article a yes or no, you'd allow the list of possible sections to be dynamic and based on your xml import.
Java variables are not "dynamic", unlink actionscript for exemple. You cannot call or assign a variable without knowing it at compile time (well, with reflection you could but it's far to complex)
So yes, the solution is to have a switch case (only possible on strings with java 1.7), or using an hashmap or equivalent
Or, if it's about importing XML, maybe you should take a look on JAXB
If you are trying to get an attribute from an object, you need to make sure that you have "getters" and "setters" in your object. You also have to make sure you define Section in your article class.
Something like:
class Article{
String section;
//constructor
public Article(){
};
//set section
public void setSection(Section section){
this.section = section;
}
//get section
public String getSection(){
return this.section;
}
I am moving from C++ to Java, and I am used to the way boost serialization works for xml. What is very good with it is:
that I only have to write one function that is used for both parsing and generating the XML. This function is basically a mapping between the field value and the name of the xml tag.
that the XML generated is light weight, and only contain the information we want to save (no information about the type of the field, the name of the class...)
I am looking for something that would have the same advantages, in JAVA. Here is a C++ example:
struct ContractDefinition
: public fme::ToStringInterface
{
public:
std::string name;
template<class archive>
void serialize(archive& ar, const unsigned int FME_UNUSED(version))
{
using boost::serialization::make_nvp;
ar & make_nvp< std::string >("name", name);
}
};
and the result looks like that:
<name>WHATEVER THE NAME IS</name>
Take a look at jaxb.