Is "set" a keyword for Java? - java

Beginner on Java, I got this piece of code from .java file from a big project which compiles
for (Var var : cfg.getArgs())
set(var);
but in my Java program there is no definition of that set method. I am just wondering whether set is a keyword of Java?

No, set is not a keyword in Java.
Member function
What you see in that snippet is a call to a method called set. Presumably a member method of the enclosing class, in which case it is identical to the more familiar syntax:
this.set(var);
Look above or below that particular snippet, and you'll most likely find the definition. It should look something like
public void set(Var var) {
....
}
Member function of super class
Note that it can also be a method of a super class. I.e., if the class is declared as
class Configuration extends SomeClass { ...
then the definition of the set method could be in SomeClass.
Here is the official list of keywords btw,
Java Language Keywords
Statically imported method
If it's not defined in the class, and you can't for your life find it in any super class, then it may be a statically imported method from some other class. In that case, look for something like
static import org.comp.Class.set;
in the top of the .java file.
Finally, if you're using Eclipse to develop, you can hit F4 or right click on the identifier and select declarations in project to jump to the definition of the method.

set is likely the name of another method in the Java code you borrowed.

According to this list, no set isn't a keyword:

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.

Cant use a public method from another class in java

I am trying to call a public constructor of a public class located in one package of my project from the main class, located in a class from another package different to the first one, but located in the same project.
I have understood that the public modifier grant you access to methods from any location inside or outside the package, so i just try to create and instance a new object of the public class first mentioned.
F.E: I try something like.... ClassName newObject = new ClassName(); from the main class
Actually, in order to be able of using that (im using netbeans IDE) I need to import the class/method I want to call, even if they have the public modifier.
My question is... is there a way of using these methods without the need of importing them to the main class ?
I am new in this webpage, so sorry if there is anything wrong with the question.
Qualification and visibility have little to do with eachother. Those are different concepts.
Visibility (enforced by access modifiers like public, protected, private and package-private) is about which class may access (i.e. call or use) it.
Qualification is about the compiler asking you: "Okay, you are mentioning a class name, but there could be thousands around with that name. Which one do you mean?"
You could use the fully qualified class Name instead.
a.b.c.MyClass myClass = new a.b.c.MyClass();
Also see
Java: import statement vs fully qualified name?
Java compiler restricts its search for classes inside the package only. In order to make use of any class belonging to a different package, you have to import it explicitly. You can read more about packages here.
Access specifiers are more from restricting the methods from being accessible by outside world. These access specifiers enforce further restrictions on top of what is enforced by packages. You can refer to this link for access specifiers.

How to extend Java class in Nashhorn JavaScript and add class member variables

I try to create an instance of a class that extends a Java class, and in that instance add some class member variables. Here's my attempt:
var ui = Java.extend(javax.swing.JPanel, {
cb : new JCheckBox("A checkbox", true),
});
However, the Nashorn interpreter throws this error:
"TypeError: function noSuchMethod() { [native code] } is not a constructor function"
What am I doing wrong? Nashorn didn't complain when I added an instance of a custom class, like se.datadosen.util.Stopwatch, but it throws this error when I try to add that JCheckBox.
(I know components are added to panels with the .add() call, but this question is really about how to add class member variables to a subclass.
Java.extend allows you to add methods implemented in JavaScript to a Java class (actually, to create a new class that subclasses the Java class). It does not allow you to add arbitrary properties, at least according to the documentation. See The Nashorn Java API, which says:
You can extend a class using the Java.extend() function that takes a Java type as the first argument and method implementations (in the form of JavaScript functions) as the other arguments." (emphasis added)
You are attempting to add an object as a property of the class, at least the way your code is presently written.
javax.swing.JCheckBox instead of JCheckBox ?

Overriding Javadoc comment on java.lang.Enum.values()

I have a very specific problem about the method java.lang.Enum.values().
I would like to override its javadoc. Very precisely, the current javadoc for this is, after I created my own enum:
public static MyClass.MyEnum[] values()
...
This method may be used to iterate over the constants as follows:
for (MyClass.MyEnum c : MyClass.MyEnum.values())
System.out.println(c);
Returns:
...
But in my company System.out calls are considered bad practice so I would like it not to be shown. My first try was to override values() but it is apparently not possible. Is there another way I can do this? Or is the only possibility to update the generated doc ?
I am also curious about why values() is not overridable. I read on other questions that "it is generated by the compiler". But can someone be more precise? It seems that it's generated from the enum's name, but it does not explain why.
values is a static method and is not subject to overriding. You cannot provide your own method to replace the generated one, and this is by specification.
There is no standard mechanism to replace the Javadoc of a method whose source code you don't control, but you could probably mess around with either the build tool, or, if all else fails, the final Javadoc HTML.
I don't think this is possible, but you could file a JDK issue and maybe provide an OpenJDK fix, if you like.
From the Oracle Java Tutorials:
The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.
So, the method values cannot be overridden, since it's a special method created by the compiler. The Eclipse IDE generates this error when you try to do so:
The enum (your enum) already defines the method values() implicitly

Use two classes in the same java file

I have file TestClass.java
package com.fido.android.sample.dsm.SoftPin.Core;
public class TestClass
{
public int mValue1;
public String mValue2;
}
Now in this file (TestClass.java) I want to declare one more class, but when I write for example:
public class SecondClass
{
// Class members goes here.
}
Compiler do not allow me to do that, if I remove public everything is Okay, but I can use SecondClass only in the TestClass.java, I can't write
SecondClass sc = new SecondClass();
out of TestClass.java class. Now I want to know if there is a way to do such thing, to have two classes in the same file and to use them from everywhere (not inner classes).
Question is: Why would you want to declare a second public class within the same Java class file? It is a rule in Java that each public class must be declared in a single class file - except for nested classes like Graham Borland pointed out.
Short answer: You can't.
That's how Java works.
You can only declare a single public class per file, with the class name the same as the file name.
You can use inner-classing as Graham suggested, or better yet, move the second class in a new file.
If you have SecondClass inside TestClass (i.e. nested inside the class definition), with public visibility, then you can refer to TestClass.SecondClass everywhere.
No, you can't, if the compiler chooses to enforce this rule from the Java Language Specification, section 7.6:
When packages are stored in a file system (ยง7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:
The type is referred to by code in other compilation units of the package in which the type is declared.
The type is declared public (and therefore is potentially accessible from code in other packages).
This restriction implies that there must be at most one such type per compilation unit.
So this is optional in that it's still "legal Java" to include more than one public top-level class in a single source file - but it's also valid for the compiler to reject it. In practice, I think every file-based Java compiler I've ever used enforces this rule.
Now you could try to find a different compiler if you really wanted, but there's a reason for this: Java programmers are used to finding the source code for a public top-level type (and usually any top-level type) in a source file with the same name.
To ask a return question provocatively: why do you want to make your source code hard to navigate?
You cannot.
What you can do is to have inner classes.
According to java conventions, A public class should be created in a separate file having same name as of class name.
So you cannot make two public classes in same file.
you can try either removing public from one class or making inner class.
Since public classes must have the same name as the source file , there can only one pulbic class inside a java file.

Categories