I have the following code:
public IQueryable<ITax> FindAllTaxes()
{
return db.Taxes;
}
I am getting the following error
Cannot implicitly convert type 'System.Data.Linq.Table<Models.Tax>' to 'System.Linq.IQueryable<Interfaces.ITax>'
I am trying to use Interface where ever I go, but not sure how to convert this, any help?
We don't have covariance of generic types yet, I'm afraid. You can do IQueryable<Tax>, but not IQueryable<ITax>. You could introduce a conversion, but it'll probably break composability, rendering it useless. You could try it though:
return db.Taxes.Cast<ITax>();
In C# 4.0, this would probably work without the extra cast (although I haven't tried it).
try this
public IQueryable<Taxe> FindAllTaxes() { return db.Taxes; }
or
public IQueryable<Tax> FindAllTaxes() { return db.Taxes; }
Related
How to change from "setLineTokenizer(new DelimitedLineTokenizer()...)" to "JsonLineMapper" in the first code below? Basicaly, it is working with csv but I want to change it to read a simple json file. I found some threads here asking about complex json but this is not my case. Firstly I thought that I should use a very diferent approach from csv way, but after I read SBiAch05sample.pdf (see the link and snippet at the bottom), I understood that FlatFileItemReader can be used to read json format.
In almost similiar question, I can guess that I am not in the wrong direction. Please, I am trying to find the simplest but elegant and recommended way for fixing this snippet code. So, the wrapper below, unless I am really obligated to work this way, seems to go further. Additionally, the wrapper seems to me more Java 6 style than my tentative which takes advantage of anonimous method from Java 7 (as far as I can judge from studies). Please, any advise is higly appreciated.
//My Code
#Bean
#StepScope
public FlatFileItemReader<Message> reader() {
log.info("ItemReader >>");
FlatFileItemReader<Message> reader = new FlatFileItemReader<Message>();
reader.setResource(new ClassPathResource("test_json.js"));
reader.setLineMapper(new DefaultLineMapper<Message>() {
{
setLineTokenizer(new DelimitedLineTokenizer() {
{
setNames(new String[] { "field1", "field2"...
//Sample using a wrapper
http://www.manning.com/templier/SBiAch05sample.pdf
import org.springframework.batch.item.file.LineMapper;
import org.springframework.batch.item.file.mapping.JsonLineMapper;
import com.manning.sbia.ch05.Product;
public class WrappedJsonLineMapper implements LineMapper<Product> {
private JsonLineMapper delegate;
public Product mapLine(String line, int lineNumber) throws Exception {
Map<String,Object> productAsMap
= delegate.mapLine(line, lineNumber);
Product product = new Product();
product.setId((String)productAsMap.get("id"));
product.setName((String)productAsMap.get("name"));
product.setDescription((String)productAsMap.get("description"));
product.setPrice(new Float((Double)productAsMap.get("price")));
return product;
}
public void setDelegate(JsonLineMapper delegate) {
this.delegate = delegate;
}
}
Really you have two options for parsing JSON within a Spring Batch job:
Don't create a LineMapper, create a LineTokenizer. Spring Batch's DefaultLineMapper breaks up the parsing of a record into two phases, parsing the record and mapping the result to an object. The fact that the incoming data is JSON vs a CSV only impacts the parsing piece (which is handled by the LineTokenizer). That being said, you'd have to write your own LineTokenizer to parse the JSON into a FieldSet.
Use the provided JsonLineMapper. Spring Batch provides a LineMapper implementation that uses Jackson to deserialize JSON objects into java objects.
In either case, you can't map a LineMapper to a LineTokenizer as they accomplish two different things.
I'm using Gson library to parse JSON objects. In particular, I've got a JSON like this:
{
"key": ["string1", "string2"]
}
and I would like to parse it in a simple String[], without building a specific object. I tried this way:
gson.fromJson(json, String[].class);
but I had an error: "Expected BEGIN_OBJECT but was BEGIN_ARRAY", I guess because of the presence of the key. Any ideas how should I fix it?
Create a class that has a key property that has type of String[] and deserialize to that.
public class Thing
{
private String[] key;
public String[] getKey() {
return key;
}
}
Thing thing = gson.fromJson(json, Thing.class);
Since tvanfosson answer is perfect, I should not add anything but in the comment you asked is it's possible to avoid creating the Thing class. Yes, it is but I think is more fragile. I'm going to show you how to do with this code:
String json = "{\"key\": [\"string1\", \"string2\"]}";
String mJson = json.replace("{\"key\":", "").replace("}","");
String[] strings = new Gson().fromJson(mJson, String[].class);
System.out.println(Arrays.asList(strings));
Of course this code runs without errors and avoids you additional classes, but think to what happens if there's some carriage return inside. It breaks, unless you user a regexp inside the replace invocation. At this point I prefer to add a class instead of thinking of right regexp and let Gson do the whole work.
I added this as response and not as comment to have enough space to explain myself, but this answer should not be taken as right response but instead as poor hack to use. It pays better to understand a bit more how Gson reasons.
I'm designing a framework and in the process I have come across an interesting but most likely basic problem. I have a base class called CoreEngine and two other classes that extend it: CoreEngine1 and CoreEngine2. I created an interface that each of these classes would implement to increase the flexibility of my project. However, I have a problem... The definition of my methods in the interface do not match the definition in each inherited class! Each class must implement the following method:
function get avatar():AvatarBase;
The problem is that CoreEngine1 and CoreEngine2 expect a different type of avatar:
CoreEngine1
function get avatar():AvatarScaling
CoreEngine2
function get avatar():AvatarPlatform
As you can see, the return type for avatar in CoreEngine1 and CoreEngine2 do NOT match the type as specified in the interface. I was hoping that since both AvatarScaling and AvatarPlatform inherit AvatarBase that I wouldn't have a problem compiling. However, this is not the case. According to Adobe's documentation, the types MUST match the interface. I am trying to follow one of the core concepts of object oriented programming to extend the flexibility of my framework: "Program to an interface rather than an implementation". The first thing that comes to my mind is that the return type of the accessor method should be of an interface type (Maybe I just answered my own question).
I'm certain this is a common problem others have run into before. Architecturally, what do you think is the best way to solve this problem? Thanks in advance!
Regards,
Will
This is a limitation of how interfaces work and are declared.
If there's inheritance that can happen with the return types, as you've described with AvatarBase and subclasses, then I think the right approach is to make the return type the lowest common denominator and just handle the resulting object on the other end. So, if you're dealing with a CoreEngine1 object, you know you can cast the result from AvatarBase to AvatarScaling. Alternately, if you don't know the object type that you are calling get avatar() on, then you can type check the returned value. The type check would then only be needed if you're looking to call a method that exists on AvatarScaling but not on AvatarBase. I don't think returning an interface type will buy you much in this case because the only things that interface can implement would be things that all forms of Avatar share, which wouldn't be any different than methods in AvatarBase.
Like HotN and Dinko mentioned, it would be best to allow get avatar() to return AvatarBase allways and then cast the returned object as the concrete subclass.
Using Dinko's example:
public /* abstract */ class CoreEngine
{
public /* abstract */ function get avatar():AvatarBase {}
}
public function CoreEngine1 extends CoreEngine
{
override public function get avatar():AvatarBase { return new AvatarScaling(); }
}
public function CoreEngine2 extends CoreEngine
{
override public function get avatar():AvatarBase { return new AvatarPlatform(); }
}
public /* abstract */ class AvatarBase {}
public class AvatarScaling extends AvatarBase
{
public function someAvatarScalingMethod():void {}
}
public class AvatarPlatform extends AvatarBase
{
public function someAvatarPlatformMethod():void {}
}
To use a method from AvatarScaling, cast the returned object:
var c1:CoreEngine1 = new CoreEngine1();
var avatarScaling:AvatarScaling = AvatarScaling(c1.avatar());
avatarScaling.someAvatarScalingMethod();
hth
I think you answered your own question... the return type would still be AvatarBase, you need to follow the signature that you specified in the interface... but you can technically return ANY descendent of AvatarBase in that function. So doing something like
return new AvatarScaling();
in CoreEngine1 would be perfectly acceptable.
Of course in your calling function you will get back an AvatarBase instance, and you will have to know what this is in order to cast to a specific subclass.
CoreEngine1 ce1 = new CoreEngine1();
AvatarScaling avatar = ce1.avatar() as AvatarScaling;
Which naming convention for conversions is standard across most languages?
convert_from_typea_to_typeb(arg)
or
convert_to_typeb_from_typea(arg)
Or is there another standard?
I'm going for the OO approach here, (in the relevant namespace) have a Convert class with a bunch of overloads To<TypeName> like so:
public class Convert
{
public Foo ToFoo(Bar instance);
public Foo ToFoo(Baz instance);
public Bar ToBar(Foo instance);
public Bar ToBar(Baz instance);
public Baz ToBaz(Foo instance);
public Baz ToBaz(Bar instance);
}
addition since php came specifically into the conversation; you cannot really do "overloading" in php, but there is a way to do it:
class ConversionException extends Exception
{
}
class Convert
{
public static function ToFoo($instance)
{
$from_type = get_class($instance);
$my_convert_method = $from_type . 'ToFoo';
if (method_exists(__CLASS__, $my_convert_method))
{
return self::$my_convert_method($instance);
}
else
{
throw new ConversionException(sprintf('Cannot convert %s to Foo.', $from_type));
}
}
protected static function BarToFoo(Bar $instance)
{
/* conversion implementation here */
}
protected static function BazToFoo(Bar $instance)
{
/* conversion implementation here */
}
/* you get the point */
}
My answer, and purely subjective, would be the one that flows logically with source to destination.
ConvertStringToInt()
or
ConvertVisitorToCustomer()
I guess in C(++) you would do it with cast operators, so none of these names would fit.
In Objective-C I've seen something like NSPointFromCGPoint(...), or you would give the old type simply in the constructor.
The only thing that I've seen very rarely are those functions with convert_x_to_y :-)
There is no cross-language standard for this kind of thing. Most languages either provide a built-in way to do this (C/C++) or encourage you to find another way around it (Java/C#).
In most object-oriented languages you shouldn't need this sort of functionality. You should try to restructure your program so that you do not need to do any explicit conversions.
However, if you really need to do this, I'd say drop the "convert" at the beginning and do <source>_to_<target>. Examples: string_to_int, int_to_float, foo_to_bar, etc. (Of course, write these in whatever case your language prefers. For example, in C#: StringToInt; in JavaScript: stringToInt.)
I am creating a method that accepts a IOBJECT parameter. there is multiple class that implement this interface. I need to figure out which type IOBJECT is. how would i go about doing that
You can use typeof, instanceof, or the 'is' operator
It's not ideal, but you can use the "is" operator. Throw it into a switch of if else statment to figure things out.
if(obj is ClassA) {
//sweetness
} else if (obj is ClassB) {
//awesomeness
}
typeof will not work, as suggested in the other reply. It will likely return "object" in all cases. instanceof will work though.
You can do getQualifiedClassName() to get the class name of the object. You can also use describeType() which gives you a more complete description of all the methods and properties of the object.
There is information about both here:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/package.html
It doesn't sound like an ideal situation though. You may want to do something where you can standardize the way you handle all items. For example:
public interface IObject {
function doSomething():void;
}
Then...
function myMethod(obj:IObject):void {
obj.doSomething();
}