Java class keyword different uses? - java

A ClassName.class returns the Class object for that particular class. That said and understood, I can't really grasp what the keyword does when used directly in a method.., then, if we write class and follow it immediately with a dot, the list that appears seems to include all that's in scope there, i.e. local variables of the method, other methods and variables(depending on whether the method is static or not), method itself, and class itself..
Coming from its first stated function above, I find myself at odds with this one: I can't tell what it's exactly doing.. way I see it, it's the same word, expect same function at heart, but that doesn't seem to be the case here
Blurry.. I know, but any insight into it is appreciated. Thx.

I get similar behaviour from Netbeans:
However, these are somewhat bogus suggestions.
class.emptyList(), despite being a suggestion, will not compile. This is probably a peculiarity of the way suggestions are computed. If there's a way to get legal code out of these suggestions, I can't think of it.
Note that you get the same suggestions if you just hit CTRL+enter (or whatever keys you have bound to suggestions) on an empty statement.
Usually there are only two circumstances to use the word class:
When defining a class, for example public class MyClass { ... }
With a dot, after a class name, to get the Class object for a type - Class<Person> clazz = Nurse.class
Sometimes you feel you'd like to have a variable called class, but it's a reserved word, so you can't. It's quite common to see variables called clazz for that reason.

Related

Check if a class exists in a specific package

I need to check if a class exists in a package.
I know I can use Class.forName to check if a class exists, but how do I verify if it is inside a specific package?
Do not use Class.forName for this.
Class.forName takes a fully qualified name. Fully qualified names include the package, but also the outer classes, and therefore, aren't going to work here:
package pkg;
class Outer {
class Inner {}
}
results in the fully qualified name, the name you'd have to pass to CFN, for Inner is: Class.forName("pkg.Outer.Inner"); - and how do you tell Outer is an outer class and not part of the package name?
Java does not have hierarchical packages; there is no relationship between pkg and pkg.subpkg, so your question hopefully does not involve 'how do I check if the package part starts with a certain string', as you shouldn't be asking that question in the java ecosystem.
Thus, let's move away from Class.forName.
Note that the class needs to be available at runtime, or it won't work. "Fortunately", if the class is not available at runtime and you want to determine the package given e.g. a fully qualified class name, because of the above issue with outer and inner classes, that job is literally impossible, so if that's what your question boiled down to, you can stop reading: No can do. Let's assume it is available at runtime.
You need a Class<?> object.
Each class is represented by an object, of the java.lang.Class<?> type. You need to obtain such an object and then you can determine which package it is in.
Strategy 1: Class.forName
Class.forName("pkg.Outer.Inner") will get you the Class<?> object and from there you can ask it what its package is, and that would get you pkg, which you presumably want to know. So that's one way: Given a string representing the fully qualified name of a class, toss it through Class.forName, and then operate on the Class object you get out of this.
Strategy 2: Class literals.
Java has special syntax to obtain the Class<?> object given a type reference. So, if you know the type reference when you write your code, you can use this:
package pkg;
class Outer {
class Inner{}
private static Class<?> innerClassObj = Inner.class;
}
However, if you can write it that way, you already know from which package that class is coming from at write time, so that makes your question entirely moot. Why try to figure out at runtime what you already know?
Just in case this is what you wanted to know: Check your imports, and in any major IDE, hold CMD (CTRL on non-macs), and click on the name, it'll take you to where it is defined, and the package will be listed right there. Or just float over it, that works in most IDEs just as well.
Strategy 3: From an object instance.
All objects have a .getClass() method which obtains the Class<?> instance representing how the object was created.
Careful though!
List<String> list = new ArrayList<String>() {
#Override public boolean add (String other) {
log.info("Added: {}", other);
return super.add(other);
}
};
This is perfectly valid, somewhat common and completely innocent java code. However, it means that now invoking list.getClass() and then asking for the name of that class gives you something like com.foo.internal.WhateverClassThatCodeShowedUpIn$1, because that is technically a subclass, and thus list is an instance of that. If you wanted to check if the object is 'of a class that is from the java.util package', then just looking at list.getClass() would incorrectly tell you it is not.
The fix is to be aware of this and to always (in a while loop) go through all the superclasses. list.getClass().getSuperclass() would resolve to the exact same instance as java.util.ArrayList.class would, invoking getSuperclass on that will get you to java.util.AbstractList.class, and from there, java.lang.Object.class and then null. java.util.List.class never shows up here - that is not a class, that is an interface. If you want those too - well, .getInterfaces() exists.
So, if you want to know: Is this object compatible with some class that is in some specific package - there is your answer. Only way is to use while loops (and if you want to check interfaces, a queue or recursive method even).
Strategy 4: Have it be given to you.
You can always just have a method that takes in a Class<?> as a parameter. Various APIs out there give you one, as well.
Okay, I have a Class<?> instance, now what?
You could call the .getPackage() method on it, but unfortunately the JVM spec dictates that this doesn't actually have to return something (it may return null). So that's not a great solution. Instead, I suggest you invoke .getName() on it, and then go to town on the string you get.
That string you get would be pkg.Outer$Inner. You can see how you can derive the package from this:
Find the last ..
If it exists, strip that and all after it.
If there is no dot at all, it's in the unnamed package.
Voila. That'll leave you with pkg.
NB: Take into account the bit written about in strategy 3: For your needs you may have to scan through the superclass and all superinterfaces, recursively.

Extending a class vs. adding boolean parameter

When writing a program in Java, if I have a special case of an object that needs to be treated differently by the main class but that does not require any additional methods, is it better to add a boolean parameter to the constructor of the object such as isSpecial and to check whether the object is special in the main class or to create a new object that extends the original?
Example:
I have a Cat class. If a cat has whiskers, I want to print "This cat has whiskers!" in the Main class.
Would it be better to have a WhiskerCat class or to simply add a boolean parameter to the Cat constructor such as hasWhiskers?
Simply add the boolean parameter. You don't want to end up with an excess of classes that do roughly the same thing. For example, in the Cat class, the default value for hasWhiskers should be false, and remain false if they don't call the constructor that explicitly requires them to specify it. Then you can have a hasWhiskers() method that returns this boolean attribute.
In general, only extend a class if the new class has additional functionality (additional methods etc) that cannot simply be tacked on to the original.
It's a problem of responsibilities: which class is doing what?
Your "main" class should not probably be aware of the internals of the "Cat" class.
In your case that means the implementation of the Cat class would probably need to be adjusted to either have a new interface that the main class could use to print that message.
Then the Cat class itself could either have that boolean, a (list of) component that make up the cat or you could go the inheritance way. This will most likely depend on the real problem: is there many more variations? is that really the only difference? are you taking a class/exam? (in the last case it might be more useful to just apply the way you've been taught).
I think the problems are about design patterns instead of coding style.
In general,if you want to add some new features in a class.
First,you should ask yourself is it a interface or a property?If it is a property,then there are two ways to tackle it.
Way 1:subclass as you metioned
Way 2:you should use delegate (i.e. add a hairclass to consider whether it is a long hair cat
or it is short hair cat.)
Just wondering, is adding a boolean the only way to recognize if the object is special? For sure there must be other characteristics that make it special?
Anyway, it's not the responsibility of the main class to know if it is. Leave what should be printed to the Cat class, not on the Main class.
In my opinion it depends on how special that attribute is.
If we consider another example:
cars...
The attribute 'sunroof' or 'navi' is quite common and has no special requirement to the car and may be part of the base class.
But a siren and flash light are quite uncommon and would be better fit if they are attributes of another extended class.

Automatically change public to private (Java)

I am doing a refactoring on code is translated from other languages into Java and I want to do it automatically. My problem is that I have a lot of methods that aren't private but are just called in the same class that they are declared and I want to make them private. I have a lot of classes and I guess if there is something that can help me to do it semi-automatically I would like to know it.
Do you know if I can look for these methods to make them private fastly? I am using Eclipse.
Replace all is one option.
But I suggest you don't do it. private and public are there for the programmer. If you only call a method from the class itself, it doesn't automatically mean it has to be private. The best thing you can do is go through them one at a time and ask yourself "should this method be part of the public interface or not?".
Personally, whenever I encounter a private method in a class which I need to use, 99% of the time I leave it private and look for a workaround. That's because I assume the original author of the code knew what he was doing. Of course, this doesn't always apply.
private is a statement of intent. It's like saying - if you need to use this from outside the class, you're doing something wrong. You shouldn't need this.
One thing to be aware of is, since it is assumed public scope, you may have classes outside of your class calling the method. If you are able to guarantee yourself that you have all possible code calling this. You can also check if the method is being use in eclipse by right mouse click on the method and use the Reference or (ctrl+shift+G) to make sure that no where is calling this method.
To actually making the change from public to private, a search and replace is probably your best bet.
Maybe one way would be replacing "public" words with "private" words on selected documents and with "Replace all" function. But it has side effects if you have "public" in the content of some code other than the method signature, e.g. inside a String maybe.
After replacing all method signatures you select, check one more time to make sure them they are in the way you wanted.

What is the proper way to declared class objects?

This is just a quick question to settle a dispute that I stumbled on a while back (sorry I don't have the link).
How I have been declaring object is as so:
class Foo {
private Bar aBar = new Bar();
...
}
Now the dispute that I found says that this is bad Java. I have no idea why he would say that, but he was quite adamant. What he proposed was that all objects should be declared in the class body, but not instantiated until the constructor. Can anyone shed light on this for me? Is it indeed better to instantiate objects in the constructor?
TFYT
~Aedon
Edit 1:
I know that I used the word dispute, but I do not intend for this to be argumentative.
In most cases it doesn't matter. My rule of thumb is:
If you're going to use the same expression to initialize the variable in all constructors, and it doesn't rely on any parameters, do it at the point of declaration.
Otherwise, you're pretty much forced to do it in the constructor anyway.
Reasoning: by initializing at the point of declaration, it's clear that the value is going to be assigned the same way regardless of the constructor and parameters. It also keeps your constructors simpler, and free of duplication.
Caveat: Don't also assign the value in a constructor, as otherwise that invalidates the previous clarity :)
I suggest you ask your colleague (or whatever) for concrete reasons for his claims that your current code is "bad". I'm sure there are valid alternative points of view, but if he can't provide any reasons, then there's no reason to pay attention IMO.
Another quick note - I'm assuming that none of the initializers need to do any significant work. If they do, that could be a point of confusion, especially if exceptions are thrown. In general, I don't like my constructors doing a lot of work.
By assigning properties in the constructor, it becomes immediately clear what code will run when you instantiate your class.
If you assign inside a field declaration, people reading the class constructor won't realize that the field is set elsewhere.
The contract of a constructor is to create an instance that is semantically valid. That is all fields are properly initialized to reasonable values and so on. For this reason, initializing everything in the constructor helps to clarify what makes a valid instance of your class. In addition, mechanisms like constructor chaining can be used to avoid repeating the same code when you have multiple constructors.
However, that is just a textbook-like theory and in real life you sometimes do the more expedient thing. Since it will make almost no difference if you instantiated objects at the point of declaration or not there need be no strong positions that leads to disputes.

Enum declared outside class scope

I went to this interview for a software developer position and they gave me a test with some corner-case-code situations, with usually 4 options to choose.
One of the questions had an enum declared outside the class scope, I promptly checked the "does not compile" answer and went ahead with the other questions.
It was something like:
enum Colors {BLUE,RED,GREEN}
class Test {
//other code, not really important with my question
}
This code actually compiles.
Besides the fact that an interview like this (might or) might not be useful to find out if one is a good developer, what worries me is: why would I declare an enum like this? Why I can only do this with enum?
I did some testing and found out that it is visible inside the class, but not to other classes.
Sidenote: I scored really poor :P. I got the max on the theory but near the lowest possibile on the corner-case-code situations. I don't think I'll get the job.
It's not just enums. Enums are just special kinds of classes. In general you can have multiple classes declared in one file (as long as no two of them are public).
No, without an access modifier, the enum is package-private. This means it can only be used by classes in the same package. And you can't only do this with an enum, classes can also be made package-private.
More info: http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
Sometimes this idiom can be sensible - for example, imagine you have an UploadHandler class (or something like that) which can return a status from an upload. It seems quite feasible to me to implement this status as an enum - and since the enum (e.g. UploadStatus) clearly "belongs" to the UploadHandler class, it seems fine to declare it in the same source file. (This does assume of course that it only needs to be package-private - if it's truly public it would need to be declared in its own file, which would probably make sense if it's not an internal thing any more).
As it happens, in this case I would probably make it a static inner class to make the relationship more explicit. But declaring multiple classes in the same source file isn't always bad and can sometimes help readability by setting the expectation that this is a borderline-trivial, subsidiary class. (By the same token, I don't think classes like this should do anything particularly complex or unexpected.)
It compiles actually, on my Eclipse ! ;-)
Several classes are allowed to be in the same file. The limitation is that a public class has to be defined in a file that has the same name.
It's visibility is 'package', so it should be visible in other classes in the same package too.
What can I do with that enum?
You can do anything you want with the above limitations...
Note : although you had it wrong, you shouldn't feel too bad, because it's not really a good practice either. In our CheckStyle configuration, outer classes in the same file like this are treated as errors !!
An enum specifies a list of constant values that can be assigned to a particular type.
It can be either inside or outside of the class.

Categories