Midlet is not abstract and does not override abstract method focusLost(com.sun.lwuit.Component) - java-me

I have a LWUIT class which has a List, the list itself contains a Label as an item.
My idea simply to make an action for the list when I focus on the label.
I get the following error, when compiling the class:
anonymous Midlet$2 is not abstract and does not override abstract
method focusLost(com.sun.lwuit.Component) in
com.sun.lwuit.events.FocusListener
String s = ("Focus me");
final com.sun.lwuit.Form f = new com.sun.lwuit.Form();
final com.sun.lwuit.List D = new com.sun.lwuit.List();
final com.sun.lwuit.Label l = new com.sun.lwuit.Label(s);
D.addItem(l);
f.addComponent(D);
D.addFocusListener(new com.sun.lwuit.events.FocusListener () {
public void focusGained(com.sun.lwuit.Label l)
{
}
public void focusLost(com.sun.lwuit.Label l)
{
}
});

All details of what is wrong with your code are in the error message, you just need to carefully read it. Look,
word anonymous and sign $ in Midlet$2 tell you something is wrong in the anonymous class.
In your code snippet, there's only one such class: new com.sun.lwuit.events.FocusListener
does not override abstract method focusLost(com.sun.lwuit.Component) means your anonymous class misses a definition of a method with such a signature (signature is method name and type of parameters)
Look closer in the methods you defined in that anonymous class, is there a method compiler is complaining about?
At the first glance, you may think it's there, there's a method called focusLost - but (!) you need to remember that signature is not only method name, but also parameters type - and (!) if you look closer, you'll find out that parameter type is not that is said to be required in error message.
Your anonymous class has method focusLost(com.sun.lwuit.Label) but error message says there should be method with different signature (different parameter type) - focusLost(com.sun.lwuit.Component).
To fix this compilation error, add to the anonymous class new com.sun.lwuit.events.FocusListener a method with required signature: focusLost(com.sun.lwuit.Component).

Related

Changing Object.toString() dynamically in Groovy has no effect when calling Integer.toString()

I injected overridden method toString into Object.metaClass:
Object.metaClass.toString ={
System.out.println("the string is $delegate")
}
and I thought that following code will execute this method:
1500.toString()
But it didn't not,nothing was printed to the console. That is what exactly confuses me: if something goes bad, then an error is to throw out; if Object.metaClass.toString is found and invoked, then the message will turn up, but why it is not working? What happened inside?
This behavior is correct, because java.lang.Integer overrides Object.toString() with its own implementation. If your assumption was correct then it would mean that you can break overridden method by forcing to use an implementation from parent class.
Consider following Groovy script:
Object.metaClass.toString = {
System.out.println("the string is $delegate")
}
class GroovyClassWithNoToString {}
class GroovyClassWithToString {
#Override
String toString() {
return "aaaa"
}
}
new GroovyClassWithNoToString().toString()
new GroovyClassWithToString().toString()
1500.toString()
Runtime.runtime.toString()
When you run it you will see something like:
the string is GroovyClassWithNoToString#3a93b025
the string is java.lang.Runtime#128d2484
You can see that GroovyClassWithNoToString.toString() called Object.toString() method and its modified version, also Runtime.toString() calls Object.toString() - I picked this class as an example of pure Java class that does not override toString() method.
As you can see overriding toString() method from Object level makes sense for classes that base on Object.toString() implementation. Classes that provide their own implementation of toString() wont use your dynamically modified method. It also explains why following code works:
Object.metaClass.printMessage = {
System.out.println("Hello!")
}
1500.printMessage()
In this example we are adding a new method called printMessage() to Object class and all classes that don't override this method will use this dynamic method we just created. Integer class does not have method like that one so it's gonna print out:
Hello!
as expected.
Also keep in mind that toString() should return a String and it's better to not print anything to output inside this method - you can end up with nasty StackOverflowError caused by circular calls to toString() method.
UPDATE: How toString() method is being picked by Groovy runtime?
Let me show you under the hood what happens when we call following script:
Object.metaClass.toString = {
System.out.println("Hello!")
}
1500.toString()
and let's see what does Groovy during the runtime. Groovy uses Meta Object Protocol (MOP) to e.g. invoke any method called in a Groovy code. In short, when you call any Java or Groovy method it uses MOP as an intermediate layer to find an execution plan for a method - call it directly or use e.g. a method that was injected dynamically.
In our case we use plain Java class - Integer. In this case Groovy will create an instance of PojoMetaMethodSite class to meta class implementation for Java class - an Integer. Every meta method is executed using one of the Groovy groovy.lang.MetaClass implementation. In this case groovy.lang.MetaClassImpl is being used. One of the last methods that picks a method to execute is MetaClassImpl.getMethodWithCachingInternal(Class sender, CallSite site, Class [] params). If you put a breakpoint in the beginning of this method and run a script with a debugger, you will see that this method is executed with following parameters:
In line 1331 you can see that helper method called chooseMethod(e.name, methods, params) is being used:
cacheEntry = new MetaMethodIndex.CacheEntry (params, (MetaMethod) chooseMethod(e.name, methods, params));
This method is responsible for picking the right method to execute when we try to invoke toString() on Integer object. Let's get there and see what happens. Here is what this method implementation looks like:
/**
* Chooses the correct method to use from a list of methods which match by
* name.
*
* #param methodOrList the possible methods to choose from
* #param arguments
*/
protected Object chooseMethod(String methodName, Object methodOrList, Class[] arguments) {
Object method = chooseMethodInternal(methodName, methodOrList, arguments);
if (method instanceof GeneratedMetaMethod.Proxy)
return ((GeneratedMetaMethod.Proxy)method).proxy ();
return method;
}
Source: https://github.com/apache/groovy/blob/GROOVY_2_4_X/src/main/groovy/lang/MetaClassImpl.java#L3158
Now let's see what parameters are received when we call our script:
What is most interesting in our case is the first element of methodOrList.data. It's a method object of:
public java.lang.String java.lang.Integer.toString()
which is the method toString() that Integer class overrides from its parent class. Groovy runtime picks this method, because it is the most accurate from the runtimes point of view - it is the most specific method for Integer class provided. If there is no toString() method overridden at the class level (e.g. Runtime class example I mentioned earlier) then the best candidate for invoking toString() method is a ClosureMetaMethod provided by us in Object.metaClass.toString = .... I hope it gives you a better understanding of what happens under the hood.
I don't think you can override the Object.toString() that way.
But this works:
Integer.metaClass.toString = { ->
System.out.println("the string is $delegate")
}
https://groovyconsole.appspot.com/script/5077208682987520

Error while building the solution in vs2012?

I've created my project in vs2008.It works fine.But when i opened the solution and try to build it in vs2012 i am getting the following error in TransactionDB.dbml page.
a partial method may not have multiple defining declarations
What could be the problem??
.net supports partial methods.
It means you write a definition in one part of the partial class and the implementation in another. Like this:
partial class MyClass
{
partial void MyPartialMethod(string s);
}
// This part can be in a separate file.
partial class MyClass
{
// Comment out this method and the program will still compile.
partial void MyPartialMethod(string s)
{
Console.WriteLine("Something happened: {0}", s);
}
}
In your case I you have the two definitions of the partial method causing the compiler to fail.
Source MSDN
The defining declaration of a partial method is the part that specifies the method signature, but not the implementation (method body). A partial method must have exactly one defining declaration for each unique signature. Each overloaded version of a partial method must have its own defining declaration.
To correct this error
Remove all except one defining declaration for the partial method.
Example
// cs0756.cs
using System;
public partial class C
{
partial void Part();
partial void Part(); // CS0756
public static int Main()
{
return 1;
}
}

non-static variable this cannot be referenced from a static context

I'm working with java me. I tried to switch to a displayable(form2) in Second.java from an okCommand in another displayble(form1) in First.java (see my previous question on that).
I got an error non-static method getForm2() cannot be referenced from a static context. I had to add the word static to form2 declaration and also at the getForm2 method in Second.java before it could work.
Problem now is that a backCommand in form2 can't switch back to form1 in First.java and it pops up the error non-static variable this cannot be referenced from a static context.
I paused and took some time to refresh myself on the language fundamentals on how the static keyword is used and I got to know that a static method is a class method and a non-static method is an instance method and that a non-static cannot call a static method unless an instance of the non-static method is created and also that a static method can't call a non-static method.
I'm really not understanding the implementation as I should, and I'd appreciate some clarification using my example above.
Here's the source below from Second.java the error is coming from form2.setCommandListener(this);
public static Form getForm2() {
if (form2 == null) {
form2 = new Form("form");
form2.addCommand(getBackCommand());
form2.setCommandListener(this);
}
return form2;
You have a static method, but are using this. But this doesn't exist. It would normally reference to an instance of the class, but you don't have one here.
If your method wasn't static and you instantiated an instance of this class then this would work.
e.g.
Second s = new Second();
Form f = s.getForm2(); // if this method wasn't static
Making that method static means little more than namespacing. There isn't an associated instance and no this.
There are couple options. First is to create a static instance of Second and use it in the getForm2:
//...
// static instance
private static Second instance = new Second(/* put constructor arguments here, if any */);
//...
public static Form getForm2() {
if (form2 == null) {
form2 = new Form("form");
form2.addCommand(getBackCommand());
form2.setCommandListener(instance); // --> replace "this" with "instance"
}
//...
From the issues you describe though, I would prefer another option - returning to design you had in previous question and use an instance of Second as an argument passed via constructor of First.
Your First.java would then have lines like:
//...
private final Second second; // instance needed for commandAction
//...
First(Second second) { // constructor with parameter
this.second = second; // save the parameter
//...
}
Then, commandAction method in First.java could use code like:
switchDisplayable(null, second.getSecondForm());
// instead of Second.getSecondForm()

#Delegate class without default constructor

How can I create a delegate class in Groovy for a class which doesn't have a default constructor? I would like to decorate JUnit's ResultPrinter but am getting an error about the missing constructor.
I don't understand your issue. I just tried this with Java's Short — which also does not have a default constructor.
Everything worked as expected, except if you didn't initialize the delegated object, you get an NPE.
Is it possible you are using #Delegate incorrectly? Delegate doesn't decorate existing classes, it allows you to use an existing classes methods in your own class. It's like extend, but without the class inheritance.
Example code:
class Foo {
#Delegate Short num
String bar
String toString() { "$bar: $num" }
}
def f = new Foo(bar: 'bob', num: 34 as Short)
println f // OK
println f.doubleValue() // OK
f = new Foo()
println f.doubleValue() // NPE
(Alternatively, providing some useful information, such as the actual error and stacktrace, and example code, will get you more useful responses.)

Problem using Lazy<T> from within a generic abstract class

I have a generic class that all my DAO classes derive from, which is defined below. I also have a base class for all my entities, but that is not generic.
The method GetIdOrSave is going to be a different type than how I defined SabaAbstractDAO, as I am trying to get the primary key to fulfill the foreign key relationships, so this function goes out to either get the primary key or save the entity and then get the primary key.
The last code snippet has a solution on how it will work if I get rid of the generic part, so I think this can be solved by using variance, but I can't figure out how to write an interface that will compile.
public abstract class SabaAbstractDAO<T> :ISabaDAO<T> where T:BaseModel
{
...
public K GetIdOrSave<K>(K item, Lazy<ISabaDAO<BaseModel>> lazyitemdao)
where K : BaseModel
{
...
}
I am getting this error, when I try to compile:
Argument 2: cannot convert from 'System.Lazy<ORNL.HRD.LMS.Dao.SabaCourseDAO>' to 'System.Lazy<ORNL.HRD.LMS.Dao.SabaAbstractDAO<ORNL.HRD.LMS.Models.BaseModel>>'
I am trying to call it this way:
GetIdOrSave(input.OfferingTemplate,
new Lazy<ISabaDAO<BaseModel>>(
() =>
{
return (ISabaDAO<BaseModel>)new SabaCourseDAO() { Dao = Dao };
})
);
If I change the definition to this, it works.
public K GetIdOrSave<K>(K item, Lazy<SabaCourseDAO> lazyitemdao) where K : BaseModel
{
So, how can I get this to compile using variance (if needed) and generics, so I can have a very general method that will only work with BaseModel and AbstractDAO<BaseModel>? I expect I should only need to make the change in the method and perhaps abstract class definition, the usage should be fine.
UPDATE:
With a very helpful response I have a slightly improved example, but an interesting dilemna:
I have this defined now, and I don't have any in or out on T here because I get errors that contradict, if out T then I get that it must be contravariantly valid and if in T then covariantly valid, so I made it invariant, since it appears VS2010 can't figure it out.
public interface ISabaDAO<T> where T:BaseModel
{
string retrieveID(T input);
T SaveData(T input);
}
I get this error, though it did compile:
System.InvalidCastException: Unable to cast object of type 'ORNL.HRD.LMS.Dao.SabaCourseDAO' to type 'ORNL.HRD.LMS.Dao.ISabaDAO`1[ORNL.HRD.LMS.Models.BaseModel]'.
I fixed two code snippets above, but it appears that variance won't work as I hoped here.
I had tried this:
public delegate K GetIdOrSave<out K>(K item, Lazy<ISabaDAO<BaseModel>> lazyitemdao)
where K : BaseModel;
but I get the same problem as with the interface, if I put out it complains, so I put in and the opposite complaint.
I think I could get this to work if this was legal:
public delegate K GetIdOrSave<K>(in K item, out Lazy<ISabaDAO<BaseModel>> lazyitemdao)
where K : BaseModel;
C# 4.0 support for covariance and contravariance when working with delegates and interfaces.
How is Generic Covariance & Contra-variance Implemented in C# 4.0?
So if you can use the generic delegate Lazy with a Interface as parameter so try somthing like this:
//covariance then you can save Giraffe as SicilianGiraffe but you cannot save Giraffe as Animal; contr-variance realization is not imposible in your case(just theoreticaly)
public interface ISabaDAO<out T> where T: BaseModel{
int retrieveID(BaseModel);
T SaveData(BaseModel);
}
public abstract class SabaAbstractDAO<T> : ISabaDAO<T>{
...
// in this case Lazy should be covariance delegate too
// delegate T Lazy<out T>();
public K GetIdOrSave<K>(K item, Lazy<ISabaDAO<BaseModel>> lazyitemdao) where K : BaseModel
{
...
return (K)itemdao.SaveData(item);// is not safe
...
}
}
public class Course : BaseModel{}
public class SabaCourseDAO : SabaAbstractDAO<Course>{}
//so you can cast SabaCourseDAO to ISabaDAO<Course> and ISabaDAO<Course> to ISabaDAO<BaseModel>
// then next invoking should be valid
GetIdOrSave(new Course (), new Lazy<ISabaDAO<Course>>(() =>
{
return new SabaCourseDAO() { Dao = Dao };
})
Cannot check it. I have not got VS2010.

Resources