cannot find symbol (doesn't recognize methods inside GregorianCalendar) - methods

Issue:
CalendarTest.java:9: error: cannot find symbol
int today = d.get(Calendar.DAY_OF_MONTH);
^
symbol: method get(int)
location: variable d of type GregorianCalendar
My code:
import java.util.*;
public class CalendarTest
{
public static void main(String[] args)
{
GregorianCalendar d = new GregorianCalendar();
int today = d.get(Calendar.DAY_OF_MONTH);
}
}
So, what I've done so far was checking the API (methods get and set won't work at all).
I've also been searching stackoverflow and google to get some help about the issue, but without any positive results.
Tried switching between Java 6 and Java 7 without any result at all.
Been doing this for Calendar instead of GregorianCalendar, but the problem still remains.
I'm operating on Ubuntu 12.04. I've no clue what's wrong since those methods are included in GregorianCalendar class (as far as API says so)
Also,
CalendarTest.java:8: error: constructor GregorianCalendar in class GregorianCalendar cannot be applied to given types;
GregorianCalendar asd = new GregorianCalendar(2000, 10, 25);
^
required: no arguments
found: int,int,int
reason: actual and formal argument lists differ in length
won't work as well. It says that parameters (int, int, int) are wrong. Well it shouldn't, should it?
Please help me get past this, since I can not move any further (doing Core JAVA 2 Basics)

The code you've posted is fine. I strongly suspect you've got another class called GregorianCalendar on your classpath. I suggest you look for it and remove it. Note that Calendar.DAY_OF_MONTH itself appears to be found correctly.
One thing you might want to try (just to see which package is at fault) is explicitly specifying the types:
java.util.GregorianCalendar d = new java.util.GregorianCalendar();
int today = d.get(java.util.Calendar.DAY_OF_MONTH);
I suspect that will work, in which case you should look for a GregorianCalendar type in the default package.
If that's still not working, it suggests your Java installation is broken.

Related

How to use EthernetManager in Xamarin Android API 19?

I am trying to make EthernetManager work in Xamarin Android API 19 to use its
getSavedConfig and updateDevInfo(EthernetDevInfo info) methods, as found here:
ftp://ftp1.digi.com/support/temp/digi-docs/reference/android/net/ethernet/ethernetmanager.html
For this I am using reflection:
Java.Lang.Object ethMn = GetSystemService("ethernet");
IntPtr eth0 = JNIEnv.FindClass("android/net/ethernet/EthernetManager");
IntPtr method = JNIEnv.GetMethodID(eth0, "getState", "(V)I");
IntPtr obj = JNIEnv.CallObjectMethod(ethMn.Handle, method);
Using getState method above to simplify the invocation.
There is a JNI example here:
https://forums.xamarin.com/discussion/12117/how-to-get-class-method-by-reflection
and a JNI reference here: https://developer.xamarin.com/guides/android/advanced_topics/java_integration_overview/working_with_jni/
The first 2 lines of my code snippet run fine i.e. the system service and class are retrieved into ethMn and e. However the 3rd lines throws an exception saying:
Java.Lang.NoSuchMethodError: no method with name='getState' signature='(V)I' in class Landroid/net/ethernet/EthernetManager;
This is odd because as can be seen from the first link I posted, getState() does exist and with the signature as entered.
I know I am missing something basic, but can't figure out exactly what. Can anyone please help? Thank you!
Depends upon the EthernetManager on your device, if there even is one, there are lots of variants since this is not a public class.
But your signature should be ()I.
i.e.:
m = JNIEnv.GetMethodID(e, "getState", "()I");
or (getEthState is a common variant of getState)
m = JNIEnv.GetMethodID(e, "getEthState", "()I");

Why should functions used for creating a Predicate be defined as static?

While reading up on the new features introduced in Java 8, I came across the concept of Predicates. I noticed that most of the examples provided on the internet and in books use static functions to create predicates.
Consider the following Apple class for example :
public class Apple {
private String color;
private int weight;
private static final int SMALL_APPLE_MAX_WEIGHT = 150;
public Apple(String color, int weight) {
this.color = color;
this.weight = weight;
}
public static boolean isGreenApple(Apple apple) {
return null!=apple && null!=apple.getColor() && "green".equals(apple.getColor());
}
public boolean isBigApple() {
return this.getWeight() > SMALL_APPLE_MAX_WEIGHT;
}
}
I can now create a new predicate as follows :
Predicate<Apple> isGreenApple = Apple::isGreenApple;
Predicate<Apple> isBigApple = Apple::isBigApple;
As shown above, I can create a predicate using both a static as well as an instance method. Which approach is the preferred approach then and why?
For a method reference, there is no difference between an instance method A.foo() and a static method foo(A), in fact, the compiler will reject a method reference as ambiguous if both exist.
So the decision whether to use an instance method or a static method does not depend on the question whether you want to create a function via method reference for it.
Rather, you have to apply the same considerations us usual. Should the method be overridable, it has to be an instance method, otherwise, if it represents a fixed algorithm, you may consider a static method, but of course, a final method would do as well.
static methods are obviously unavoidable when you are not the maintainer of the class whose instance you want to process, in other words, when the containing class has to be different than the class of the instance. But even if the class is the same but you feel that it could be placed in another (utility) class as well, declaring it as static might be the better choice.
This holds especially when there are more than one parameter and the first one isn’t special to the operation, e.g. max(Foo,Foo) should be a static method rather than an instance method max(Foo) on Foo.
But in the end there are different programming styles out there and the answer is that method references do not mandate a particular programming style.
Regarding why there are so many examples using static methods; well I don’t know enough examples to decide whether your observation is right or just a subjective view. But maybe some tutorial writers are themselves not aware about the possibility to refer to an instance method as a function taking the method receiver as first argument.
I think, there are examples, like
Predicate<String> empty=String::isEmpty;
Predicate<CharSequence> isHello="hello"::contentEquals;
which are worth to be shown in tutorials to emphasize that you are not required to create methods specially intended to be used as method references, but that in fact there are a lot of already existing methods, static and non-static, to be directly usable with method references.
What I am more interested in knowing is why are all examples on predicates shown using static methods?
The reference appears on the Class as no additional argument is required.
Any specific reason for not using instance methods?
For non-static methods that would make sense. In the case of
Predicate<Apple> isBigApple = Apple::isBigApple;
Predicate needs a argument so it takes this. An example of a non-method call would be something like
List<Apple> bigApples = new ArrayList<>();
apples.stream().filter(Apple::isBigApple).forEach(bigApple::add);

How to write Scala 2.9 code that will allow dropping into an interpreter

I am not sure how to write code that will allow dropping into an interpreter into Scala 2.9 code. This question is a follow-up to this one, which asked what the Scala equivalent of,
import pdb
pdb.set_trace()
was from Python. The advice given there was primarily for Scala 2.8, and the related packages no longer exist in their previous form. Namely,
scala.nsc.tools.nsc.Interpreter.{break, breakIf} have been moved to scala.nsc.tools.nsc.interpreter.ILoop.{break, breakIf}
DebugParam is now NamedParam in scala.tools.nsc.interpreter
As noted in the original post, the class path of the parent process is not passed to the new interpreter automatically, so a workaround was presented here. Unfortunately, many of the classes/methods invoked there have now changed, and I'm not quite sure how to modify the code the behave as "expected".
Thanks!
EDIT: Here is my test code, which at current compiles and runs, but attempting to execute anything in the debugger results in the application freezing if compiled by scalac and executed by scala
import scala.tools.nsc.interpreter.ILoop._
object Main extends App {
case class C(a: Int, b: Double, c: String) {
def throwAFit(): Unit = {
println("But I don't wanna!!!")
}
}
// main
override def main(args: Array[String]): Unit = {
val c = C(1, 2.0, "davis")
0.until(10).foreach {
i =>
println("i = " + i)
breakIf(i == 5)
}
}
}
EDIT2: As my current setup is running through sbt, I have discovered that this topic is covered in the FAQ (bottom of the page). However, I do not understand the explanation given, and any clarification on MyType would be invaluable.
EDIT3: another discussion on the topic without a solution: http://permalink.gmane.org/gmane.comp.lang.scala.simple-build-tool/1622
So I know this is an old question, but if your REPL is hanging, I wonder if the problem is that you need to supply the -Yrepl-sync option? When my embedded REPL was hanging in a similar situation, that solved it for me.
To set -Yrepl-sync in an embedded REPL, instead of using breakIf you'll need to work with the ILoop directly so you can access the Settings object:
// create the ILoop
val repl = new ILoop
repl.settings = new Settings
repl.in = SimpleReader()
// set the "-Yrepl-sync" option
repl.settings.Yreplsync.value = true
// start the interpreter and then close it after you :quit
repl.createInterpreter()
repl.loop()
repl.closeInterpreter()

F# constructor syntax - overiding and augmenting new

I have a non-disposable class with Open/Close syntax that I'd like to be able to use, so I'm trying to inherit from it, and work the Open into the new and the Close into Dispose.
The second part is ok, but I can't work out how to do the Open:
type DisposableOpenCloseClass(openargs) =
inherit OpenCloseClass()
//do this.Open(openargs) <-- compiler no like
interface IDisposable
with member this.Dispose() = this.Close()
(cf. this question which I asked a long time ago, but I can't join the dots to this one)
Key is as this:
type OpenCloseClass() =
member this.Open(x) = printfn "opened %d" x
member this.Close() = printfn "closed"
open System
type DisposableOpenCloseClass(openargs) as this =
inherit OpenCloseClass()
do this.Open(openargs)
interface IDisposable
with member this.Dispose() = this.Close()
let f() =
use docc = new DisposableOpenCloseClass(42)
printfn "inside"
f()
As Brian suggests, you can use the as this clause. However, in F#, it is usually recomended to use subclassing (inheritance) only when there is a really good reason for that (e.g. you need to implement some virtual class and pass it to a .NET library).
If I was implementing your example, I would probably prefer function returning IDisposable using a simple object expression:
let disposableOpenClose(openargs) =
let oc = new OpenCloseClass()
oc.Open(openargs)
{ new IDisposable with
member this.Dispose() = oc.Close() }
let f() =
use docc = disposableOpenClose(42)
printfn "inside"
To some point, this is just a personal preference, but I think it is a preferred option, because it is simpler than using inheritance (although I don't have any document to link here :-)). Also, the compiled code may be a bit simpler, because handling as this may require some runtime checks.

What's so great about Func<> delegate?

Sorry if this is basic but I was trying to pick up on .Net 3.5.
Question: Is there anything great about Func<> and it's 5 overloads? From the looks of it, I can still create a similar delgate on my own say, MyFunc<> with the exact 5 overloads and even more.
eg: public delegate TResult MyFunc<TResult>() and a combo of various overloads...
The thought came up as I was trying to understand Func<> delegates and hit upon the following scenario:
Func<int,int> myDelegate = (y) => IsComposite(10);
This implies a delegate with one parameter of type int and a return type of type int. There are five variations (if you look at the overloads through intellisense). So I am guessing that we can have a delegate with no return type?
So am I justified in saying that Func<> is nothing great and just an example in the .Net framework that we can use and if needed, create custom "func<>" delegates to suit our own needs?
Thanks,
The greatness lies in establishing shared language for better communication.
Instead of defining your own delegate types for the same thing (delegate explosion), use the ones provided by the framework. Anyone reading your code instantly grasps what you are trying to accomplish.. minimizes the time to 'what is this piece of code actually doing?'
So as soon as I see a
Action = some method that just does something and returns no output
Comparison = some method that compares two objects of the same type and returns an int to indicate order
Converter = transforms Obj A into equivalent Obj B
EventHandler = response/handler to an event raised by some object given some input in the form of an event argument
Func = some method that takes some parameters, computes something and returns a result
Predicate = evaluate input object against some criteria and return pass/fail status as bool
I don't have to dig deeper than that unless it is my immediate area of concern. So if you feel the delegate you need fits one of these needs, use them before rolling your own.
Disclaimer: Personally I like this move by the language designers.
Counter-argument : Sometimes defining your delegate may help communicate intent better. e.g. System.Threading.ThreadStart over System.Action. So it’s a judgment call in the end.
The Func family of delegates (and their return-type-less cousins, Action) are not any greater than anything else you'd find in the .NET framework. They're just there for re-use so you don't have to redefine them. They have type parameters to keep things generic. E.g., a Func<T0,bool> is the same as a System.Predicate<T> delegate. They were originally designed for LINQ.
You should be able to just use the built-in Func delegate for any value-returning method that accepts up to 4 arguments instead of defining your own delegate for such a purpose unless you want the name to reflect your intention, which is cool.
Cases where you would absolutely need to define your delegate types include methods that accept more than 4 arguments, methods with out, ref, or params parameters, or recursive method signatures (e.g., delegate Foo Foo(Foo f)).
In addition to Marxidad's correct answer:
It's worth being aware of Func's related family, the Action delegates. Again, these are types overloaded by the number of type parameters, but declared to return void.
If you want to use Func/Action in a .NET 2.0 project but with a simple route to upgrading later on, you can cut and paste the declarations from my version comparison page. If you declare them in the System namespace then you'll be able to upgrade just by removing the declarations later - but then you won't be able to (easily) build the same code in .NET 3.5 without removing the declarations.
Decoupling dependencies and unholy tie-ups is one singular thing that makes it great. Everything else one can debate and claim to be doable in some home-grown way.
I've been refactoring slightly more complex system with an old and heavy lib and got blocked on not being able to break compile time dependency - because of the named delegate lurking on "the other side". All assembly loading and reflection didn't help - compiler would refuse to just cast a delegate() {...} to object and whatever you do to pacify it would fail on the other side.
Delegate type comparison which is structural at compile time turns nominal after that (loading, invoking). That may seem OK while you are thinking in terms of "my darling lib is going to be used forever and by everyone" but it doesn't scale to even slightly more complex systems. Fun<> templates bring a degree of structural equivalence back into the world of nominal typing . That's the aspect you can't achieve by rolling out your own.
Example - converting:
class Session (
public delegate string CleanBody(); // tying you up and you don't see it :-)
public static void Execute(string name, string q, CleanBody body) ...
to:
public static void Execute(string name, string q, Func<string> body)
Allows completely independent code to do reflection invocation like:
Type type = Type.GetType("Bla.Session, FooSessionDll", true);
MethodInfo methodInfo = type.GetMethod("Execute");
Func<string> d = delegate() { .....} // see Ma - no tie-ups :-)
Object [] params = { "foo", "bar", d};
methodInfo.Invoke("Trial Execution :-)", params);
Existing code doesn't notice the difference, new code doesn't get dependence - peace on Earth :-)
One thing I like about delegates is that they let me declare methods within methods like so, this is handy when you want to reuse a piece of code but you only need it within that method. Since the purpose here is to limit the scope as much as possible Func<> comes in handy.
For example:
string FormatName(string pFirstName, string pLastName) {
Func<string, string> MakeFirstUpper = (pText) => {
return pText.Substring(0,1).ToUpper() + pText.Substring(1);
};
return MakeFirstUpper(pFirstName) + " " + MakeFirstUpper(pLastName);
}
It's even easier and more handy when you can use inference, which you can if you create a helper function like so:
Func<T, TReturn> Lambda<T, TReturn>(Func<T, TReturn> pFunc) {
return pFunc;
}
Now I can rewrite my function without the Func<>:
string FormatName(string pFirstName, string pLastName) {
var MakeFirstUpper = Lambda((string pText) => {
return pText.Substring(0,1).ToUpper() + pText.Substring(1);
});
return MakeFirstUpper(pFirstName) + " " + MakeFirstUpper(pLastName);
}
Here's the code to test the method:
Console.WriteLine(FormatName("luis", "perez"));
Though it is an old thread I had to add that func<> and action<> also help us use covariance and contra variance.
http://msdn.microsoft.com/en-us/library/dd465122.aspx

Resources