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
emanresu tnuocca
Sep 2, 2011

by Athanatos
Modifying the getter makes sense.

Yeah there is no real harm as my menu class would never call this method if its current 'focus' is on the top-level container, but this is only due to my hard coded menu logics, I was looking into this from a fool proofing perspective, though I guess you're probably correct and I should just handle this as an exception.

Thanks!

Adbot
ADBOT LOVES YOU

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Kenishi posted:

I've been working some Java alg exercises on paper and I've just had a brainfart.

code:
// Node are single linkedlist nodes
// Assume less and cur are valid.
Node temp = cur.next;
cur.next = less.next;
less.next = cur;
cur = temp;
'cur' will equal cur.next after this all executes. And less.next will still be the old cur value. Correct?

Yes, cur will be the old cur.next, less.next will be the old cur, and the old cur will have its .next no longer point to the old cur.next but instead the old less.next.

T. J. Eckleburg
Apr 10, 2007
sorry about the clock.

My background: I am a technical writer, and I just got a job working with developers who write in Java. Previously I'd been working with Python developers. In school I took a class in python and did well (and in fortran, ugh). I've done a little self-study, and I've got halfway through the codeacademy lessons for python without much trouble. I have a personal interest in learning to code and might want to switch into a developer position sometime later in my career.

My question: How hard is java to learn compared to python? Basically, I know the standard advice for a newbie is to learn python first, but I have reason to switch to learning java if that's feasible. I just don't know how steep the learning curve is. I also don't really know where to start on learning by myself, since there are no codeacademy lessons for java and I'm not in school anymore. Would it be worth signing up for an intro class at a community college like this one or purchasing the textbook for that course, or another textbook?

This might be an unusual question, but thanks for the help anyway. :)

Kenishi
Nov 18, 2010
Java should be easier to learn than python in some respects because Java doesn't handle tuples and lists natively. The only thing that might be hard for someone that only knows Python is the fact that Java is type sensitive. Python uses 'duck typeing' while Java uses explicit declaration of what things have to be. I don't use Python as deeply as it can be used so I can't comment on everything but I do know lambda expressions were recently added to Java 8, so that brings Java closer to what Python can do.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

I graded/tutored for a class that served as the first introduction to Java for students who had previously learned Python, and the biggest issues I noted come down to the fact that Java is a more rigid language. You have to give the type of all variables rather than letting it be figured out, as mentioned, and all code must be in a class file, the files have to be named correctly for them to even compile, and a few other things you'll pick up as you go. If Python is your only really strong language, you'll likely learn a lot just by virtue of learning a new language, as Java will probably differ from Python in ways you didn't even expect could be different.

Depending on how confident you feel, the official Java Tutorials (especially Getting Started and Learning The Java Language) offer a good, if a bit brief, walkthrough on setting up the environment, the language syntax, and common classes you'll be using.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...
Java also needs an IDE whereas with Python you really can get away with a smart text editor for a long time. Pick up Eclipse or IntelliJ and spend a little time learning to use it.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

carry on then posted:

Depending on how confident you feel, the official Java Tutorials (especially Getting Started and Learning The Java Language) offer a good, if a bit brief, walkthrough on setting up the environment, the language syntax, and common classes you'll be using.

CodingBat is pretty good for practicing some problems and getting your feet wet with the basics of the language, too

Kenishi
Nov 18, 2010

Volmarias posted:

Java also needs an IDE whereas with Python you really can get away with a smart text editor for a long time. Pick up Eclipse or IntelliJ and spend a little time learning to use it.
I don't know if I'd go so far as to say it needs an IDE, but you'd be incredibly stupid to not be using one.

Most IDEs can check syntax and scope as you type (I assume due to the Just-in-Time compiling nature of Java) so you can catch errors. Also due to the strong Type casting of Java, the IDEs can more easily (and correctly) do intellisense suggestions. Other use for an IDE being that it simplifies the issue of setting up Classpaths for when you build JARs/WARs.

Kenishi fucked around with this message at 01:00 on Jul 14, 2014

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

This is probably the most 'no poo poo' thing ever but I was learning some Eclipse keyboard shortcuts the other day (we all have our hobbies) and I found out about Alt+\ :swoon:

I mean it's no ctrl+space but it's pretty cool

hooah
Feb 6, 2006
WTF?

baka kaba posted:

This is probably the most 'no poo poo' thing ever but I was learning some Eclipse keyboard shortcuts the other day (we all have our hobbies) and I found out about Alt+\ :swoon:

I mean it's no ctrl+space but it's pretty cool

Did you mean Alt+/? I searched the first few web pages that came up in a search for "Eclipse keyboard shortcuts", and none of them had Alt+\.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

Kenishi posted:

I don't know if I'd go so far as to say it needs an IDE, but you'd be incredibly stupid to not be using one.

You don't need an IDE in the same way that you don't need the API docs handy nor a modern computer nor a debugger.

If you're doing more than a trivial project, you need an IDE.

quote:

Most IDEs can check syntax and scope as you type (I assume due to the Just-in-Time compiling nature of Java) so you can catch errors. Also due to the strong Type casting of Java, the IDEs can more easily (and correctly) do intellisense suggestions. Other use for an IDE being that it simplifies the issue of setting up Classpaths for when you build JARs/WARs.

And then there are the timesavers, like never having to manually manage your exports.

And then there are the mental aides, like being able to see a tree of all possible call stacks at a particular method, or a class hierarchy, or being able to just jump directly to the right method definition for a particular subclass.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Plus an integrated debugger, stuff like a nice Git plugin in Eclipse's case, all kinds of refactoring magic, the ability to find declarations or references, pop-up documentation... I think IDEs can be pretty overwhelming at first, but once you actually get on with making something in one you start to actually learn what everything's for, and how incredibly useful it is.

Hell, they can actually help you to learn the language, with all the handy feedback and suggestions they give you when you do something even a little :raise: I don't know exactly where the dividing line between jacked up text editor and IDE lies, but they're definitely super helpful environments to work in

hooah posted:

Did you mean Alt+/? I searched the first few web pages that came up in a search for "Eclipse keyboard shortcuts", and none of them had Alt+\.

Yeah sorry, that'll teach me to phone post. The one all the way over there (that doesn't work with Alt Gr but whatever).

Hope I didn't get your hopes up there

baka kaba fucked around with this message at 02:55 on Jul 14, 2014

TheresaJayne
Jul 1, 2011

Volmarias posted:

Java also needs an IDE whereas with Python you really can get away with a smart text editor for a long time. Pick up Eclipse or IntelliJ and spend a little time learning to use it.

You can do Java and Python with Vi if you need to, I prefer an IDE but at a push Notepad++ is brilliant for any language.

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

Kenishi posted:

Java should be easier to learn than python in some respects because Java doesn't handle tuples and lists natively.

Huh? :confused:

ArrayList, LinkedList, Vector, Stack...

Kenishi
Nov 18, 2010
Those are part of the Java standard library. If I have to import the thing to use it then its not natively part of the language. Plus I've always found the manipulation of lists/tuples in Python to be a lot easier than using the Java library ones.

emanresu tnuocca
Sep 2, 2011

by Athanatos
Guys I have a stupid question related to my previous question a few posts back.

Is there any way at all to override a field using field declarations in a subclass or is this something I have to do either by overriding the setter\getter methods or alternatively through defining a constructor in the super class?

i.e I have
code:
Public class Snoop{

private int everyday = 420;

public int getEveryday(){
return this.everyday;}
}
and
code:
Public class Dogg extends Snoop(
private int everyday = 840;
}
so Dogg.getEveryday() always returns 420 in this example, is there anyway to override the field in the declaration?

Thanks in advance

FateFree
Nov 14, 2003

emanresu tnuocca posted:

Is there any way at all to override a field using field declarations in a subclass or is this something I have to do either by overriding the setter\getter methods or alternatively through defining a constructor in the super class?

You could technically override the field with the Reflection api, but I certainly wouldn't suggest that. In pure java the field is private and immutable so you can't override it with a subclass. In general you would either override the getter method, or as you said add a constructor that takes the argument. Or you could leave out the constructor and rely on getters and setters themselves, but that works best for optional fields since someone may never call the setter method before using the object.

Chas McGill
Oct 29, 2010

loves Fat Philippe

emanresu tnuocca posted:

Guys I have a stupid question related to my previous question a few posts back.

Is there any way at all to override a field using field declarations in a subclass or is this something I have to do either by overriding the setter\getter methods or alternatively through defining a constructor in the super class?

i.e I have
code:
Public class Snoop{

private int everyday = 420;

public int getEveryday(){
return this.everyday;}
}
and
code:
Public class Dogg extends Snoop(
private int everyday = 840;
}
so Dogg.getEveryday() always returns 420 in this example, is there anyway to override the field in the declaration?

Thanks in advance
I don't know for sure, but you might have to override the getEveryDay() method to return the subclass field rather than using the inherited method.

code:
public class Dogg extends Snoop
{
int everyDay = 840;
    
    @Override
    public int getEveryDay()
    {
        return this.everyDay;
    }
}

Chas McGill fucked around with this message at 12:58 on Jul 14, 2014

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...
That assumes that the value never changes. Since the field is not final, that's probably not a good idea. I would do this via having a protected constructor that sets this value, and a public constructor that calls through to the protected constructor with appropriate defaults.

Also, magic numbers :(

emanresu tnuocca
Sep 2, 2011

by Athanatos
Thanks guys. yeah apologies for the weed jokes I wanted to inject some humor into the question, I guess I failed.

The motivation for thinking about this issue was that I was creating a simple text menu and I was looking for ways to simplify the menu logics as much as possible, I basically wanted my classes to each have a field that references an object from an enum class that specifies the String to display and an array of ints that specify the valid user inputs and indeed it would seem that for this purpose it would be 'more correct' to require this menu object to be initialized in the super's constructor and require the sub-classes to instantiate the super only using the permitted constructor.

Overriding the getters is possible but makes less sense in this context.

So, once again, thanks.

emanresu tnuocca fucked around with this message at 15:00 on Jul 14, 2014

pliable
Sep 26, 2003

this is what u get for "180 x 180 avatars"

this is what u fucking get u bithc
Fun Shoe

Kenishi posted:

Those are part of the Java standard library. If I have to import the thing to use it then its not natively part of the language. Plus I've always found the manipulation of lists/tuples in Python to be a lot easier than using the Java library ones.

Oh, I consider anything part of the standard library to be "native", but I see what you mean. And yeah, I completely agree that lists/tuples in Python are way easier than Java.

Before I used Python, I came from a C/Java background, and tuples blew the poo poo out of my mind. The ability to return tons of things as one tuple is sexy as gently caress

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

emanresu tnuocca posted:

Thanks guys. yeah apologies for the weed jokes I wanted to inject some humor into the question, I guess I failed.

The motivation for thinking about this issue was that I was creating a simple text menu and I was looking for ways to simplify the menu logics as much as possible, I basically wanted my classes to each have a field that references an object from an enum class that specifies the String to display and an array of ints that specify the valid user inputs and indeed it would seem that for this purpose it would be 'more correct' to require this menu object to be initialized in the super's constructor and require the sub-classes to instantiate the super only using the permitted constructor.

Overriding the getters is possible but makes less sense in this context.

So, once again, thanks.

You cannot @Override variables, only functions. If you define a member value in a Subclass that is also defined in the Superclass, you "shadow" the definition in the superclass - any methods defined in the subclass will use the variable defined in the subclass, and any methods defined in the superclass will use the value defined in the superclass.

The typical way of allowing subclasses to override a value from a superclass is by making the superclass abstract:

code:
abstract class Snoop {
  public void getErryDay() {
    System.out.println(getSmokingValue() + "; smoke erry day.");
  }

  protected abstract int getSmokingValue();
}

class Dogg extends Snoop {
  @Override
  protected int getSmokingValue() {
    return 420;
  }
}

class Lion extends Snoop {
  @Override
  protected int getSmokingValue() {
    return 840;
  }
}
... although I'm not convinced that this is the best solution to your particular problem; it's basically storing state in the Class, which is an anti-pattern. It encourages needless creation of new classes (files) that need to be maintained. It is likely that your problem would be better solved by creating a generic skeleton of a text menu, and then passing in some sort of Map or List of valid options.

Lord Windy
Mar 26, 2010
In Intellij, is there a way to put a 'build artifact' button up around where the run button is? I'm making a project and due to how I'm making my folder structure it is just going to be easier to run a Jar than faff about changing strings.

TheresaJayne
Jul 1, 2011

Lord Windy posted:

In Intellij, is there a way to put a 'build artifact' button up around where the run button is? I'm making a project and due to how I'm making my folder structure it is just going to be easier to run a Jar than faff about changing strings.

The build menu option is next to the run menu option

But you can also set a hot key for build artifacts
I used to build my webpage output with CTRL-SHIFT-'

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

rhag posted:

Apparently TestNG can: http://stackoverflow.com/questions/2669576/order-of-execution-of-tests-in-testng
Another possible way could be to have test methods that run other methods in whatever order they want. Those other methods would not be marked as test. Of course, if you have special JUnit annotations (@Before, @After, @RunWith, etc.) that those "tests" require ... good luck.
I know that it's probably a thing that has to be done by yesterday, but I would strongly consider refactoring/rewriting them so that they can be run independently. It will bite you in the butt later on, and it's not gonna be pretty.

Yeah I think refactoring & rewriting them is the only way I can get this thing to build faster (with parallel execution). It just seems so daunting though, there are a shitload of tests. I was thinking maybe I should set up an automated script that can run them one by one and then not which ones are failures, so I can narrow down the list of poorly written tests.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!
Running a J2EE container, works fine with -Xmx2g, but when increased to -Xmx6g it starts throwing errors:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded.

Everything I read indicates that increasing the heap size is the way to solve this problem, but in our case it caused it. I can't think of any possible reason why this would happen. What's wrong with it?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Kilson posted:

Running a J2EE container, works fine with -Xmx2g, but when increased to -Xmx6g it starts throwing errors:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded.

Everything I read indicates that increasing the heap size is the way to solve this problem, but in our case it caused it. I can't think of any possible reason why this would happen. What's wrong with it?

:confused: This is the first answer on the first result of google. http://stackoverflow.com/a/4371691/102483

quote:

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

Which probably means you've got a memory leak in your application.

vyst
Aug 25, 2009



Does anyone know if something has changed in the most recent Java 8 JRE release in regards to the deployment.security.use.user.home.java.policy deployment.properties parameter? We have it set to true as we have a workstation that requires some specific grant permissions that we bounce off of the .java.policy file in %USERPROFILE% from the workstation and even though the parameter shows up as true in the dump of deployment properties from the console it doesn't seem to be detecting/utilizing the .java.policy file in the user's profile.

It worked fine in JRE 1.8_05 but this 1.8_11 seems to be causing issues. For context the newest JRE 7 update 65 works fine as well. I don't mind sticking with 1.8_05 since it's not a high demand machine but I was curious if anyone had any ideas or issues with this.

For context of what the %USERPROFILE% java.policy contains:
code:
grant {
permission javax.sound.sampled.AudioPermission "record";
permission java.net.SocketPermission "www.DOMAIN.com:80","connect,resolve";
};

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

Janitor Prime posted:

:confused: This is the first answer on the first result of google. http://stackoverflow.com/a/4371691/102483

I know what the error means. I don't know why it would happen only when I *increase* the heap size.

quote:

Which probably means you've got a memory leak in your application.

No, the error is on startup. Also, works perfectly fine with smaller heap size.

pigdog
Apr 23, 2004

by Smythe
Besides -xmx , what are the rest of the options the JVM is running with?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Kilson posted:

I know what the error means. I don't know why it would happen only when I *increase* the heap size.


No, the error is on startup. Also, works perfectly fine with smaller heap size.

Whoa that sounds neat, I assumed it came up after it had been running for a while but on startup is totally strange and means some other jvm settings are fighting with it.

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

pigdog posted:

Besides -xmx , what are the rest of the options the JVM is running with?

It's a J2EE container (Sailfin), so there are a ton of JVM options. These are the ones defined in the config file that seem at least halfway relevant:

-XX:+UseConcMarkSweepGC
-XX:+CMSClassUnloadingEnabled
-XX:+CMSPermGenSweepingEnabled
-XX:MaxPermSize=384m
-server
-Dsun.rmi.dgc.server.gcInterval=3600000
-Xmx2048m
-XX:NewRatio=2

I tried it on my local machine with the increased heap size (and all the same options) and didn't get the GC overhead error. There are a lot of differences between the machines, though, so I don't think it tells me anything. The box the error happened on is a VM, if that makes any difference.

pigdog
Apr 23, 2004

by Smythe
Any other information, like how many CPU cores available, and what version of the JVM?

Try increasing -XX:NewRatio to 8 or 16 for a start.

Max Facetime
Apr 18, 2009

Does the VM have enough real memory to give to the JVM?

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!
Supposedly the error happened with -Xmx4g also, but I can't directly confirm that.

java version "1.7.0_45"
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)

The VM has 2 CPU cores and 8GB memory available to it. Nothing else is really running on the machine. That should be enough real memory for the JVM.

On my local machine with the same amount of memory, I can start the server with -Xmx8g without issue, even with a billion other things running in the background. The JVM doesn't care about how much memory is physically available until the heap actually becomes full enough for it to matter.

Unfortunately, the machine with the problems is not a machine I have access to, so I can't play around with it. I've looked at a couple VMs with similar allocations and haven't seen the problem there.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Here's a problem that I've been running into surrounding the black-loving-magic of Captured types:

Java code:
public class EnumDeserializer implements JsonDeserializer<Enum<?>> {
    private static final Logger log = LoggerFactory.getLogger(EnumDeserializer.class);
 
    @Override
    public Enum<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            @SuppressWarning("unchecked")
            final Class<? extends Enum<?>> clazz = (Class<? extends Enum<?>>) Class.forName(typeOfT.getTypeName());
            final String strValue = json.getAsString();
 
            // see if there is an exact match first
            final Optional<? Extends Enum<?>> exactMatch = Enums.getIfPresent(clazz, strValue);
            if (exactMatch.isPresent()) {
                return exactMatch.get();
            }
 
            //if there is no exact match, return the first case-insensitive match
            for (Enum<?> e : clazz.getEnumConstants()) {
                if (strValue.equalsIgnoreCase(e.name())) {
                    return e;
                }
            }
        } catch (ClassNotFoundException| ClassCastException e) {
            log.error("Got an unexpected type; substituting null", e);
        }
 
        return null;
    }
}
What I want is a GsonProvider that translates strings into enums correctly, regardless of capitalization. (I don't want to explain the difference between "SECONDS" and "seconds" to my users.)

Java code:
final Gson gson = GsonBuilder.registerTypeHierarchyAdapter(Enum.class, new EnumDeserializer()).create();

final ChronoUnit unit = gson.fromJson("\"SeCoNDs\"", ChronoUnit.class);
My IDE doesn't detect an issue, but on compile, I get:

code:
Error:(24, 65) java: method getIfPresent in class com.google.common.base.Enums cannot be applied to given types;
  required: java.lang.Class<T>,java.lang.String
  found: java.lang.Class<capture#1 of ? extends java.lang.Enum<?>>,java.lang.String
  reason: inferred type does not conform to equality constraint(s)
    inferred: capture#2 of ?
    equality constraints(s): capture#2 of ?,capture#1 of ? extends java.lang.Enum<?>
I think the compiler's issue is that it doesn't understand that the type of the optional is the same as the type of clazz. Anyone have any brilliant ideas that leave a given instance of EnumDeserializer capable of deserializing any Enum?

Sedro
Dec 31, 2008

Gravity Pike posted:

Here's a problem that I've been running into surrounding the black-loving-magic of Captured types:
I think it's because of the recursive definition Enum<E extends Enum<E>>. You write Class<? extends Enum<?>> but you have no way to say that the first ? type is the same as the second ? type.

You can parameterize a class/method to assert that those two types are the same:
Java code:
public class EnumDeserializer implements JsonDeserializer<Enum<?>> {
    private static final Logger log = LoggerFactory.getLogger(EnumDeserializer.class);
 
    @Override
    public <T extends Enum<T>> Enum<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            @SuppressWarning("unchecked")
            final Class<T> clazz = (Class<T>) Class.forName(typeOfT.getTypeName());
            final String strValue = json.getAsString();
 
            // see if there is an exact match first
            final Optional<T> exactMatch = Enums.getIfPresent(clazz, strValue);
            if (exactMatch.isPresent()) {
                return exactMatch.get();
            }
 
            //if there is no exact match, return the first case-insensitive match
            for (T e : clazz.getEnumConstants()) {
                if (strValue.equalsIgnoreCase(e.name())) {
                    return e;
                }
            }
        } catch (ClassNotFoundException| ClassCastException e) {
            log.error("Got an unexpected type; substituting null", e);
        }
 
        return null;
    }
}
Obviously that doesn't implement your interface any more. You could parameterize the class instead which would still implement your interface but that's still probably not what you want (you don't want a deserializer from some specific enum, you want a deserializer for *all* enums).

The better option (often the best option when dealing with Java generics) is to not deal with Java generics. Just drop the <>, deal with the erased types and move on with your day.

Java code:
public class EnumDeserializer implements JsonDeserializer<Enum<?>> {
    private static final Logger log = LoggerFactory.getLogger(EnumDeserializer.class);
 
    @Override
    public Enum<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            final Class clazz = Class.forName(typeOfT.getTypeName());
            final String strValue = json.getAsString();
 
            // see if there is an exact match first
            final Optional exactMatch = Enums.getIfPresent(clazz, strValue);
            if (exactMatch.isPresent()) {
                return (Enum<?>) exactMatch.get();
            }
 
            //if there is no exact match, return the first case-insensitive match
            for (Object o : clazz.getEnumConstants()) {
                Enum<?> e = (Enum<?>) o;
                if (strValue.equalsIgnoreCase(e.name())) {
                    return e;
                }
            }
        } catch (ClassNotFoundException| ClassCastException e) {
            log.error("Got an unexpected type; substituting null", e);
        }
 
        return null;
    }
}

Max Facetime
Apr 18, 2009

Kilson posted:

Unfortunately, the machine with the problems is not a machine I have access to, so I can't play around with it. I've looked at a couple VMs with similar allocations and haven't seen the problem there.

No physical access or no access at all, not even remote? Connecting to it with Java VisualVM would be my next step to see what's happening inside the JVM when it's having problems.

Gravity Pike posted:

I think the compiler's issue is that it doesn't understand that the type of the optional is the same as the type of clazz. Anyone have any brilliant ideas that leave a given instance of EnumDeserializer capable of deserializing any Enum?

Would something like this work? I didn't try running it or anything...

Java code:
class EnumDeserializer<E extends Enum<E>> implements JsonDeserializer<Enum<E>> {

		@Override
		public E deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
			throws JsonParseException {
			try {
				@SuppressWarnings("unchecked")
				Class<E> clazz = (Class<E>) Class.forName(typeOfT.getTypeName());
				String strValue = json.getAsString();
				// see if there is an exact match first
				
				Optional<E> exactMatch = Enums.getIfPresent(clazz, strValue);
				if(exactMatch.isPresent()) {
					return exactMatch.get();
				}
				//if there is no exact match, return the first case-insensitive match
				for(E e : clazz.getEnumConstants()) {
					if(strValue.equalsIgnoreCase(e.name())) {
						return e;
					}
				}
			} catch(ClassNotFoundException | ClassCastException e) {
				throw new JsonParseException(e);
			}
			return null;
		}
	}

TheresaJayne
Jul 1, 2011

Kilson posted:

Supposedly the error happened with -Xmx4g also, but I can't directly confirm that.

java version "1.7.0_45"
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)

The VM has 2 CPU cores and 8GB memory available to it. Nothing else is really running on the machine. That should be enough real memory for the JVM.

On my local machine with the same amount of memory, I can start the server with -Xmx8g without issue, even with a billion other things running in the background. The JVM doesn't care about how much memory is physically available until the heap actually becomes full enough for it to matter.

Unfortunately, the machine with the problems is not a machine I have access to, so I can't play around with it. I've looked at a couple VMs with similar allocations and haven't seen the problem there.

I have seen VMs work as 32bit even when supposed to be 64,
I have a 64 bit machine at work but am running a 32 bit eclipse (company build)

I have seen on my machine with 8gb of ram that java can only access the 32 bit amount. meaning i can max use -Xmx1524m

as -Xmx1525m causes a cannot create VM error.

Adbot
ADBOT LOVES YOU

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I tried to be fancy with a search field the following way:
code:
    private void filterFieldFocusGained(java.awt.event.FocusEvent evt) {                                        
        if (searchTerm == null) {
            filterField.setText("");
        }
        filterField.setForeground(UIManager.getColor("TextField.foreground"));
    }                                       

    private void filterFieldFocusLost(java.awt.event.FocusEvent evt) {                                      
        if (searchTerm == null) {
            filterField.setText(EMPTY_SEARCH_MESSAGE);
            filterField.setForeground(UIManager.getColor("TextField.inactiveForeground"));
        }
    }
That is, when the field is empty, I put in a message indicating what it's for, but to avoid then searching for the message, I have the searchTerm variable. Now I have a problem that I can't paste the clipboard into the empty field from a popup menu (keyboard shortcuts work). I'm not sure how to approach this - maybe mouse events, or just scrap the message system and replace it with the regular popup hint. What do you goons think?

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