Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
zootm
Aug 8, 2006

We used to be better friends.
I didn't see one of these in the generic thread, so I guess it's just a matter of time.

Here's a thread for small questions relating to everyone's favourite programming language, Java. Chuck your questions up here.

:siren: Attention! Java is not JavaScript :siren:
Despite their similar names the languages are hugely different; questions relating to JavaScript should be directed to the Web Development Megathread

I'm going to follow this with a post on IDEs/tools/etc. Anyone who wants stuff added to that post or contact me or whatever.

zootm fucked around with this message at 18:57 on May 21, 2008

Adbot
ADBOT LOVES YOU

zootm
Aug 8, 2006

We used to be better friends.
Hefty information post
Here's the promised post on tools.

IDEs
A quick note on IDEs: Java is very verbose, so autocompletion is handy when working on it for any period of time. Luckily Java has some really great IDEs handy:

NetBeans IDE - Open source, developed primarily by Sun. Gets a lot of features based around whatever Sun is currently pushing, uses Ant as its package format (meaning it's easy to run your build remotely) and has a really nice GUI editor, along with excellent support for Ruby on Rails should you decide to run, screaming, from Java at some point. Also comes with a fairly good profiler which I would recommend more highly if it hadn't crashed and burned when I was trying to profile something over a transatlantic link the other day.

Eclipse - Another open source IDE, a little bit more flexible than NetBeans, but does more stuff for you. This was clearly better than NetBeans for a long time so this is what most teams use these days. Has a huge wealth of plugins (of variable quality) for the various frameworks available for Java. Also Bubblegum Wishes recommends this series of videos teaching Java from the ground up using Eclipse.

IntelliJ IDEA - Costs money, but pretty much nobody who tries it ever goes back. I've not used it, but I don't think I've ever heard a negative review.

Another note, though - it might be worth learning Java without these tools. They do a lot for you, and you will miss out on a lot of the subtleties of how Java works.

Finding problems
Debuggers and profilers (all of the tools above have at least the former), as with most languages, can be invaluable in finding Java problems. It's always worth knowing how your dependencies work, too, since it's the cause of a lot of misconceptions.

Preventing problems
Another tip is to use FindBugs to find common errors in your code. It may give you a lot of "false" positives, but if you keep your code clean you get a much nicer protection against the dumb mistakes that we all make sometimes than you get from "it compiles". I've run this ever since spending 2 hours with a workmate trying to find the cause of weird behaviour which turned out to be caused by someone doing == comparison on a boxed integer value (:eng101: this doesn't do what it looks like it does).

For those of you who like to be doubly paranoid, PMD does this sort of job too. PMD works on source code (rather than compiled bytecode) though, which makes it a whole bunch easier to, among other things, add your own rules. This gives you the freedom to add a check on something you know you do a lot, which is handy. It's probably for more-advanced or -paranoid users to run both, though, and FindBugs will likely be easier and more productive if you only want to use one. :)

Also, run your compiler with the "-Xlint" flag. This turns on all the warnings. This is a good thing. If you look at your code and see a warning that you decide is unwarranted (sadly there are some things that just don't work well with generics without warnings), you can add the @SuppressWarnings( "warningType" ) annotation to the method in questions, but do not do this until you are confident you understand the reason for the warning.

Your code should be clean of warnings from both the compiler and FindBugs, unless you have a drat good reason to the contrary. :argh:

zootm fucked around with this message at 13:26 on Jul 15, 2009

zootm
Aug 8, 2006

We used to be better friends.

csammis posted:

Can one use IntelliJ or Netbeans if they're developing Java RCP applications that target the Eclipse framework itself, or does that lock one into having to use Eclipse? I'm doing this at work, but I can't friggin' stand Eclipse. It's slower than an rear end in a hat.
Running Java 6 makes a big difference to performance, other than that I've not had a huge problem with Eclipse. I imagine you'll be missing a lot of tools if you try to do this sort of project outside of Eclipse but it's unlikely it's genuinely impossible.

zootm
Aug 8, 2006

We used to be better friends.

Belgarath posted:

Not strictly a Java question, but, does anyone know if Eclipse has anything similar to visual studio's #region ?
Yes, but you need a plugin. If you grab the "code folding" plugin from the update centre described on this page, you can do it by going to Preferences... Java/Editor/Folding, change to use the "Coffee-Bytes" folding implementation, enabling the "user-defined" folds, and then entering folds like this:
code:
// [start] Blah blah blah
private int thisIsJustCode;
// [end]
You might need to reload any open editors to see the change. You can customise the start and end text if you want, as well.

Incidentally this feature is available by default on Netbeans which uses an XML syntax like this:
code:
// <editor-fold desc="Blah blah blah">
private int thisIsJustCode;
// </editor-fold>
:)

zootm
Aug 8, 2006

We used to be better friends.
I'm not sure about JCreator since I've never used it, and the other ones are basically like I noted in the second post of this thread; is there anything specific you'd like to know?

zootm
Aug 8, 2006

We used to be better friends.

rotor posted:

You won't be able to write to it, IIRC.
Yeah, the classpath is essentially read-only (which I think makes a lot of sense, considering).

Leehro posted:

Does anyone have a quick tutorial or example for one of the EE persistence APIs? Everything I come across seems to be part of some framework.
You know, I don't think I've seen the javax.persistence stuff being used without Hibernate, but I'm aware it can be done. This tutorial seems pretty generic as regards the API, other than the fact that it's based on Glassfish for setting stuff up. They're using Toplink there which affects the configuration (as you'd expect it to), all the stuff mentioned works in Hibernate too, as far as I'm aware.

Other than that the Javadoc for the API is actually pretty good.

zootm
Aug 8, 2006

We used to be better friends.

Alan Greenspan posted:

http://forum.java.sun.com/thread.jspa?threadID=300557&start=45&tstart=-1

Someone developed a cute hack I use to modify the classpath at runtime for plugin reasons.
For what it's worth I think rotor meant you couldn't write to locations on the classpath through the classpath/ClassLoader system itself, rather than talking about modifying the classpath at runtime. That's a neat trick though, a few systems do things like that and it never occurred to me that it wouldn't be trivial.

zootm
Aug 8, 2006

We used to be better friends.

FuzzyBuddha posted:

Ok, a bit late but... I want to thank you for this suggestion, if for no other reason than it tags errors as I type. I'm a horrible typer and this has already saved a lot of headache.
Using "ctrl-space" you'll probably never have to type anything again. :)

zootm
Aug 8, 2006

We used to be better friends.
Yeah, using generics at runtime is pretty much a dead end in the current implementation. It's just a compiler restraint (so you can, for example, get access to stuff like that by using an annotation processor, but that's unlikely to be what you want).

zootm
Aug 8, 2006

We used to be better friends.

ReaperUnreal posted:

The java doc is of no help

quote:

Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.
ObjectInputStream(java.io.InputStream)

You're causing deadlock by waiting for input before it's been produced in the same thread.

zootm fucked around with this message at 10:13 on Mar 21, 2008

zootm
Aug 8, 2006

We used to be better friends.

ReaperUnreal posted:

Huh, how did I not see that? Thanks for the help, looks like I'll be reorganizing things. This'll be fun, having to create input and output streams inside a loop. Honestly, some times, I wish I was using C instead of Java.
More generally, why are you serialising and deserialising Java objects in one method?

nik9000 posted:

Once you learn Ant, learn Maven. Its better because its more than a build tool, its a project management tool.
Maven's always a point of contention; a lot of people don't like it. I'm not personally a fan myself, I find its behaviour a little too opaque and wide-ranging. It's respected by a lot of other people too, though, it's just a bit of a "love it or hate it" thing.

zootm fucked around with this message at 18:57 on Mar 21, 2008

zootm
Aug 8, 2006

We used to be better friends.

Brain Candy posted:

Immutable objects definitely nice for many things, but they come at a price. Strings, for example are immutable and the JVM does all sorts of optimization with them. But you'll also notice that there are special helper classes, StringBuilder and StringBuffer, just to create new Strings. In general, every time you change an immutable field you have to create a new object.
On the other hand, so long as you make properly immutable objects they're pretty cheap in comparison to normal objects for the JVM; their behaviour in the garbage collector is much more favourable since they stay in the "young" generation and are readily collected.

zootm
Aug 8, 2006

We used to be better friends.
It entirely depends on what you want to do, and what your requirements are. Java has support for pretty much every method of parsing XML out there.

DOM allows you to traverse and manipulate an XML document as an object representing its structure.
SAX and StAX are stream parsers which scale well but essentially mean you have to maintain any state that you need yourself. StAX is a more modern "pull" parser which is a lot easier to use.
JAXB allows you to bind structured XML documents to and from corresponding basic "bean" objects automatically.
XPath allows you to query a loaded XML document for a given "path" allowing you to quickly query parts of the document.

zootm
Aug 8, 2006

We used to be better friends.

Fehler posted:

Thanks, but I thought Swing and SWT were different things. Can I actually use Swing classes together with SWT?
They are, I think Kerris is a little confused. I wouldn't advise using both SWT and Swing in one program, but I've not too much experience with SWT so don't know what class you want for doing that form of popup.

As regards the SWT-and-extra-software thing, SWT does require extra stuff to be bundled per-platform since it has native components. Swing does not because it comes with the JRE.

zootm
Aug 8, 2006

We used to be better friends.

Fehler posted:

It seems like the whole bundling of native software for SWT would be a bit annoying, so do you think I should just move to Swing? It's not like I put much thought into what to use when I started...
Use both and see which one you like. I don't think packaging it is too hard, but if you use custom controls sometimes that can be a pain.

Fehler posted:

Are there any good Swing tutorials out there that explain the basics for somebody who knows nothing about Java GUIs?
I'm afraid not, but Netbeans has a GUI designer for Swing and I'm pretty sure there's a bunch of tutorials on its site.

Fehler posted:

Also, is it correct that Swing is the one with that ugly blue-silverish GUI? Any way around that?
Yes, but it also has a native look-and-feel for Windows, OS X, and GTK+ (Linux), you can turn it on programmatically. The blue thing is just guaranteed to work on all platforms (I think it's been replaced with something marginally nicer recently, too).

zootm
Aug 8, 2006

We used to be better friends.
"start" ignores input. Your Java code is working fine, but start spawns and starts a new console window for you and that's all it does.

What is it you're trying to do? There's bound to be a better way to do this?

zootm
Aug 8, 2006

We used to be better friends.
That would be a better idea, yeah. If you could invoke something like tail -f (I realise that's not a Windows program) it'd also follow the output of a log file.

If you're just wanting to catch logging, however, use a standard logging toolkit like log4j or java.util.logging or Commons Logging or whatever and write a log "target" for that which just outputs the logging information to a window or whatever you like. There's no good reason not to use "proper" logging and doing this right will give you a lot more freedom if this is important to you. Popping up an "echo" window natively doesn't seem like a good solution.

zootm fucked around with this message at 17:45 on Apr 2, 2008

zootm
Aug 8, 2006

We used to be better friends.

epswing posted:

Yep, I'm using log4j extensively, this is just to present the user with some visual feedback that what MyApp is running is actually running.
You don't need to capture stderr or stdout then, surely? Just capture the logging information directly and display it in whatever component you want.

zootm
Aug 8, 2006

We used to be better friends.

epswing posted:

What do you mean by "Just capture the logging information directly"? I'm spawning a process, how else do you propose I capture it's stdout/err?

Ah, I had thought you were running it in the same JVM, presumably you've a reason for not doing so. Just capture in and out, yeah.

zootm
Aug 8, 2006

We used to be better friends.

ColdPie posted:

Basically a utility function that compares two strings in different ways based on the bitflags. The code's for work, so I don't have it on me, but the flags are something like COMP_CASE_INSENSITIVE, COMP_BEGINS_WITH, COMP_ENDS_WITH, COMP_CONTAINS and so on. It's a whole lot easier to maintain one function and a couple bitflags than a few dozen functions with various combinations of the above options. The functions signature is essentially static void compare(String expected, String found, int flags).
Yeah, you probably want enums, assuming you're using Java 5 or newer. The EnumSet class will let you do the 'bitflag' thing in a typesafe way while also getting the full functionality of the Set interface. It's implemented as bitflags too so you get that time efficiency.

zootm
Aug 8, 2006

We used to be better friends.

TRex EaterofCars posted:

The VM will mark it collectible after its containing block's scope ends unless it's referenced somewhere else currently in scope or static, like a Map or a List of some kind. Note that it's just marked for collection, the actual collection happens at some other point.
The mark actually occurs separately as well, but this is basically it. In general just make sure you're not referring to an object you don't want any more and the JVM will do the right thing.

TRex EaterofCars posted:

Like you said, you can set it to null manually and call System.gc(); but absolutely no guarantees are made about when the memory consumed by that class will be reclaimed, if ever.
I don't think setting it null even guarantees the JVM will be able to see that it's unreachable. In general one should never, ever rely on stuff like that. Also I don't think System.gc() is guaranteed to do anything, it's just a "hint" which is only useful for debugging, if that.

adante posted:

Actually I cannot get the key or list of keys either (maybe you can, if so please share how :dance: ).
Have you tried just attaching a debugger and introspecting the object using that?

zootm
Aug 8, 2006

We used to be better friends.

BELL END posted:

I was under the impression that HashMaps don't allow more than one value to be stored with the same key, each subsequent call to put(k) overwrites what is already at k.
Yep. From the Javadoc:

quote:

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this key, the old value is replaced by the specified value.
The Commons Collections (I link to collections15 since it's the "generic" version) contains a MultiMap collection type for these sorts of semantics.

Edit: Also TRex's suggestion is the "traditional" way of doing this, and will work if you don't want to pull a JAR dependency. It's just a little bit more work to deal with the collection yourself.

zootm
Aug 8, 2006

We used to be better friends.

TRex EaterofCars posted:

Well I'll be goddamned. It must be a side effect of working in an environment devoid of intellectual curiosity but I never even bothered to check Commons for something like this. Thanks.
It's one of those things that you don't usually find out about until someone you're working with starts using it :)

Glad it's helped you too :)

zootm
Aug 8, 2006

We used to be better friends.
You can code with it fine in Netbeans, just reference the JAR and the libraries that it requires. The Netbeans visual designer is based on Swing and it's very unlikely you'll find an SWT designer for Netbeans, though.

zootm
Aug 8, 2006

We used to be better friends.

Drumstick posted:

Component2 will show, but component wont show up at all. By themeselves, they will be up and working just fine, just not together...
Swing works with layout managers for components, and I think the default one just holds one item. I think reading up on layout in Swing might be your best course of action here.

With some layouts you need to pass the "position" where the item should appear as well - with BorderLayout you can choose NORTH, SOUTH, EAST, WEST, or CENTER, for example.

zootm
Aug 8, 2006

We used to be better friends.

Drumstick posted:

okay thanks! i will look into that right away. I havent had to add two components into a frame before, thanks again
Here's the Sun tutorial, this section concerns layout. If you're hand-cranking Swing you probably wanna skip the stuff about the NetBeans UI designer in the overall trail, which is very nice but insulates you pretty much entirely from the layout code.

zootm
Aug 8, 2006

We used to be better friends.

Bonus posted:

The other day I was thinking, is there any reason why Java doesn't have return type polymoprhism? I mean like having public String foo() and public int foo() and then the one that gets called depends on what kind of type of return value the caller expects. This works really nicely in languages like Haskell and I see nothing in Java that prevents it form having this feature.
Because of polymorphism of types this would reduce the obviousness of the return type. For example given:
code:
public String foo();
public StringBuilder foo();
What would the following do?:
code:
Object bar = foo();
You could use something similar to the generic method disambiguation stuff but it would be a fairly huge new language feature:
code:
Object bar = this.[String]foo();
One would need to have language syntax for explicitly expressing which one of the functions one is calling, which would make Java even more verbose (and in cases where it could guess the type, arguably more difficult to read), for very little actual expressive benefit. Essentially this works in Haskell because the type system is so much stronger.

zootm
Aug 8, 2006

We used to be better friends.
I'm fairly sure you cannot do this in Scala, for what it's worth. I'll have a look tonight if I remember though.

Also the fact that you can do it in Jaskell does not mean that the bytecode or the JVM supports it directly. A lot of JVM languages encode such concepts (the multiple inheritance in Scala, for example, is not something that JVM bytecode supports directly).

zootm
Aug 8, 2006

We used to be better friends.

TRex EaterofCars posted:

I understand what you mean, but the JVM docs specifically state that it does not restrict overloaded method returns.
Cool, just checking. Is that how Jaskell works? It seems strange to have a JVM language that Java can't call.

zootm
Aug 8, 2006

We used to be better friends.

TRex EaterofCars posted:

I actually do not know how Jaskell is implemented. I kinda wrote that post quickly and should have put the word "also" in there somewhere. :p
Sorry I don't want to seem like I'm digging in at you, I'm just interested!

zootm
Aug 8, 2006

We used to be better friends.

Fehler posted:

How do I save an XML document I created with org.w3c.dom.Document to a file?

Flying somewhat blind:

code:
Source source = new DOMSource( doc );
Result result = new StreamResult( new FileOutputStream( filename ) );

Transformer transformer = TransformerFactory.newInstance().newTransformer();

transformer.transform( source, result );
That might well work. I have not tried it, however. The default "transform" is identity if you're wondering what the deal is.

zootm
Aug 8, 2006

We used to be better friends.

JingleBells posted:

The JAXP tutorial has the following example: http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPXSLT4.html
So essentially that code example is right :). Excellent. I knew all that time fiddling with XML in Java was not in vain.

I guess it's worth noting that that does require JAXP, which isn't standard in Java until I think Java 5 or 6.

zootm fucked around with this message at 12:21 on May 3, 2008

zootm
Aug 8, 2006

We used to be better friends.

Fehler posted:

Looks like it works, thanks! I guess something like doc.save(path) would have been too easy...
The DOM does not supply a way to save files, so it's not in the API. That sort of stuff is always a bit weird.

zootm
Aug 8, 2006

We used to be better friends.
Did you remove the absolute path link to the library in question? That could cause it problems. I've certainly gotten relative paths to work fine without error markers many times before so it's not something that can't be fixed.

zootm
Aug 8, 2006

We used to be better friends.

adante posted:

Howdy, if I have some Class<?> object (in my case, returned from a Field#getType() during reflection), how can I tell if the class represented by this object implements a particular interface or class? I guess this is the equivalent to the instanceof operator, except for the class type and not an object.
what you want is Class.isAssignableFrom( Class<?> ).

So something like the following, based on your example.
code:
boolean bIsAnA = A.class.isAssignableFrom( bClass );
boolean bIsAC = C.class.isAssignableFrom( bClass );
Both variables should be true.

zootm
Aug 8, 2006

We used to be better friends.
I'm pretty sure that can't be done. And I don't think it's something that would be good to have in code anyone would use in any case.

zootm
Aug 8, 2006

We used to be better friends.

BELL END posted:

Looks like it's a javascript question and he's in the wrong thread (apologies if I'm wrong!) it's happened a few times in this thread already. Maybe zootm could add a quick "Java != Javascript" and a link to the web development thread to the OP?
Done. :)

I'm interested to know what language the stuff within the <%= %>-delimited block is; I know Rails uses that but I don't think & concatenates strings in Ruby. The only think I could think of which would be used for web programming is VB?

zootm
Aug 8, 2006

We used to be better friends.

Twitchy posted:

You are looping over all the input / output in the seperate threads, but updating them all on the Event Dispatch thread (i.e. SwingUtilities.invokeLater(), which is the same no matter what JFrame you're using). Because you're looping over and invoking the Event Dispatch thread constantly it's locking up the other GUI. Could you not invoke the append() method at the end, and save the looping part in a StringBuilder or something?
Batching the input would probably be a good idea, but waiting until the entire stream is read absolutely would not fit this use-case; it would only show anything once the processes had completely stopped.

Furthermore the invokeLater method just appends update events to the queue, unless there was a lot of events (which the last post shows that there really isn't) you can't really block the UI thread like that. And even then I don't think the effect would be the one shown there.

epswing: I'm still worried that the stream reader stuff is running in the UI thread for some reason (the symptoms fit too well, dammit). Can you breakpoint on it (any line) in a debugger and check the full stacktrace doesn't have any Swing stuff in it?

zootm
Aug 8, 2006

We used to be better friends.

Twitchy posted:

Ah, it seems zootm is probably right, how are you making the threads?
To be clear I was talking to epswing about this on IRC last night and it sounded like he was doing the right thing here, I just wanted to double-check.

Twitchy posted:

Instead of doing a proper debug if you want the easy way to find out just do
code:
System.out.println(Thread.currentThread().getName());
to find out if it's running on an independent thread.
This would probably work too, assuming the Swing thread has a sensible name (I think it does?).

Adbot
ADBOT LOVES YOU

zootm
Aug 8, 2006

We used to be better friends.

epswing posted:

The thread creating the ProcessBuilder and both threads sucking up with stdout/err are isEventDispatchThread() == true.
Then the sucking threads are not being run in separate threads, they're running in the same thread as UI, for whatever reason. That result seems to mean that everything is running in the same thread.

epswing posted:

I loving hate GUI/Swing work. This is the kind of stuff that makes me want to quit my job and go into pig farming. It's challenging, but for all the wrong reasons. :smith:
For what it's worth most GUI frameworks are like this. The one that bugs me most is Winforms on .NET Compact Framework; it's like the normal framework with all of the stacktraces and error messages removed.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply