Reference an anonymous class? - java

I am developing a plugin for an RCP application.
Within the plugin.xml, I need to register certain classes at a given extension point.
One of these classes is an anonymous (?) class defined like this:
package de.me.mypackage;
import org.something.AnotherClass;
public class ClassOne {
...
public static AnotherClass<ClassOne> getThat() {
return new AnotherClass<ClassOne>() {
...
};
}
}
Is there any way to reference AnotherClass<ClassOne> within the plugin.xml?
I already tried something like de.me.mypackage.ClassOne$AnotherClass but that does not work. Do I have to declare that class within its own file to be able to reference it?

As far as I know, it would have a numeric index:
class Bla {
public static void main(String[] args) {
(new Runnable() {
public void run() {
System.out.println(getClass().getName()); // prints Bla$1
}
}).run();
}
}
After compiling, you get:
$ ls *.class
Bla$1.class Bla.class
That said, you can't rely on the numbering in case the source file is modified.
Can you instead define a static inner class, like:
public class ClassOne {
public static class MyClass extends AnotherClass<ClassOne> {
public MyClass(/* arguments you would pass in getThat()? */) {
...
}
...
}
public static AnotherClass<ClassOne> getThat() {
return new MyClass(...);
}
}

I need to say the obvious here - you should make it a named class if you want to refer to it. Whether you can access it otherwise is a technical curiosity (that I don't happen to know the answer to), not something you should actually do in production.

The dollar sign only comes into play in the class's binary name; in Java source, just use de.me.mypackage.ClassOne.AnotherClass.class.

Related

Want to call a non-static Interface method in a static method. How?

I facing a real hard problem in my code snippet.
I want to learn how to use Interface in Java the correct way.
So for this I have my Application-Class...
package inversionUsage;
public class Application {
public static void main(String [] args) {
String standard = "Standard version!";
if (FeatureDecisions.checkEnabledFeatures("new-feature1")) {
System.out.println("Implement new feature...");
}else {
System.out.println(standard);
}
}
}
Then I made a Interface...
package inversionUsage;
public interface AppConfiguration {
boolean isEnabled(String searchFeature);
}
I want to use the Interface in another class:
package inversionUsage;
import java.util.Arrays;
public class FeatureDecisions implements AppConfiguration{
public String [] enabledFeatures;
public String [] _implNewFeature = fetchFeatureTogglesFromSomehere();
public static boolean checkEnabledFeatures(String searchFeature) {
return isEnabled(searchFeature);
}
#Override
public boolean isEnabled(String searchFeature) {
if (Arrays.asList(_implNewFeature).contains(searchFeature)) {
return true;
}else {
return false;
}
}
private String [] fetchFeatureTogglesFromSomehere() {
// TODO get the CONFIG from somewhere
enabledFeatures = new String [2];
enabledFeatures[0] = "new-feature1";
enabledFeatures[1] = "new-feature2";
return enabledFeatures;
}
}
So the workflow is:
1. I start the Application
2. Main method checks the enabled features via FeatureDecisions.java
3. In Feature Decisions i implemented the Interface
I getting the error:
Cannot make a static reference to the non-static method isEnabled(String) from the type FeatureDecisions
May Someone can help me out?
The only way to use an instance method is to have an instance on which to call it. Your checkEnabledFeatures is static, so it doesn't receive an instance you can use (as this). To use an instance method, it would need to create an instance. But obviously that's not what you want here.
Java's interface construct is for defining the interface that instances implement. Java doesn't have the concept of a "static interface" that a class must implement. On the rare occasions when that's needed, it's usually implemented using reflection (perhaps with a class-level annotation to indicate that the class has the necessary feature).
You would have to instantiate the FeatureDecisions class.
public static boolean checkEnabledFeatures(String searchFeature) {
return new FeatureDecisions().isEnabled(searchFeature);
}
or make all members static.
Additional info: There are frameworks like togglz that do this for you.
There's no way to do that. The closest can get is to use the singleton pattern (though lots of people - myself included - would discourage it).
public enum FeatureDecisions implements AppConfiguration
{
INSTANCE;
public String [] enabledFeatures;
public String [] _implNewFeature = fetchFeatureTogglesFromSomehere();
public boolean checkEnabledFeatures(String searchFeature) {
return isEnabled(searchFeature);
}
#Override
public boolean isEnabled(String searchFeature) {
//...
}
}
Your call would then change from:
FeatureDecisions.checkEnabledFeatures(...)
to
FeatureDecisions.INSTANCE.checkEnabledFeatures(...)
It's also worth noting that checkEnabledFeatures doesn't actually do anything besides defer to isEnabled. You could scrap the former and just call the latter directly.

Why Groovy Enums has no access to class variables?

Could not find any documentation that explains why class variables are not accessible from within enums. Consider this example:
package groovy;
public class Universe {
static String test = "test";
enum Planet {
EARTH {
#Override
void doSomething(){
System.out.print(test);
}
};
abstract void doSomething();
}
public static void main(String[] args) {
Universe.Planet.EARTH.doSomething(); // No such property: test for class: groovy.Universe$Planet$1
}
}
I am aware that this code is also perfect Java code. Though it works as expected using JRE but not with Groovy's runtime environment which makes me even more curious. Is there any proof for the difference? Thanks
Groovy needs some help to find Universe's variable. Here's a link to some official documentation if you want to read up on a few differences between Java and Groovy. Here's an email discussion that touches on this some. For anyone unfamiliar with enums, they're static objects, so no accessing instance objects or variables. Which leads us to our answer, static variable needs to be referenced in a static way (via class, not an instance).
Also, if you try to use inner classes before Groovy 1.7 you're going to have a bad time (you can't).
public class Universe {
static String test = "testing";
enum Planet {
EARTH {
#Override
void doSomething(){
System.out.print(Universe.test);
}
};
abstract void doSomething();
}
public static void main(String[] args) {
Universe.Planet.EARTH.doSomething(); // No such property: test for class: groovy.Universe$Planet$1
}
}

Unable to access variables in different classes

package penny_pinch_v2;
public class Prizes {
public static String[] prizes = { "Puzzle", "Poster", "Ball", "Game", "Doll" };
}
===========Separate Class File============
package penny_pinch_v2;
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(prizes[1]);
}
}
I'm trying to access the array 'prizes' in a different class, but it keeps saying that 'prizes' cannot be resolved. If you could tell me how to fix this that would be great.
If you are referencing a static field in another class you will need to use the name of that class to reference the field, so basically you need to change your main to this:
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(Prizes.prizes[1]);
}
}
This is called a namespacing issue. Let's pretend you could do what you're trying to do. What if you make another class called Prizes2 and put another variable in it, also named prizes? How does RunPennyPinch know which prizes variable it should be using?
Perhaps you could solve this problem by saying, "only one prizes variable is allowed to exist in any program at one time". If this were a real limitation, you would quickly run out of meaningful names to give to variables.
The solution that Java came up with is namespacing: To give a variable a context it lives in. Two variables can have the same name, but as long as they have a different context, they won't clash. The price you pay is you have to tell the program which context you want to use when you're referring to a variable.
Here's how to fix the problem:
package penny_pinch_v2;
public class Prizes {
public static String[] prizes = { "Puzzle", "Poster", "Ball", "Game", "Doll" };
}
//===========Separate Class File============
package penny_pinch_v2;
public class RunPennyPinch {
public static void main(String[] args) {
System.out.print(Prizes.prizes[1]);
}
}
There's something else you should know: If you don't explicitly state a context, it defaults to using this as the context. As an unrelated example, these two methods do the same thing and both work:
package foo;
public class Bar {
public String baz = "Puzzle";
public void impliedThis() {
System.out.println(baz);
}
public void explicitThis() {
System.out.println(this.baz);
}
}
You have to prefix the variable with the class name as the variable is not within the RunPennyPinch class.
System.out.print(Prizes.prizes[1]);
You may also have to import the Prizes class, depending on your set-up.
The variable itself doesn't exist in that context. It's a static member of another class. So you need a reference to that class:
System.out.print(Prizes.prizes[1]);
The main advantage of static is that you dont have to create an object to access that variable. You just have to call that variable by Classname.variablename (Classname is the name of class in which that variable was present)
System.out.print(Prizes.prizes[1]);

Why to use variables of the same type of the current class in which they are?

I just found a Java example that uses variables typed as the current class itself. I can't understand why and when to use something like this! It's not explained by the author of the book because it's just a part of code of an example about other stuff! Could anyone help me to understand the utility of this approach? Is it related to something like "Singleton design pattern"? Furthermore I also tried to instantiate test1 and test2 but I got an error!
public class Test {
public Test() {
Test test1;
Test test2;
}
}
The original snippet is about nested classes:
public class Tree {
ExampleNode master;
public Tree() {
}
//...
class ExampleNode {
ExampleNode rightNode;
ExampleNode leftNode;
//...
void printMaster() {
System.out.println( master );
}
}
}
A simple example of where this would be useful is in a linked list, where each node needs a reference to its neighbour(s).
Use can create object of a class inside that class to call a class method. Consider the following example:
public class SomeClass {
public void callMethod() {
}
public static void main(String... args) {
SomeClass sc = new SomeClass();
sc.callMethod();
}
}
We cannot call a non static or instance method from a static method without using the instance of the class where the method belongs to. Right?
There is no relation with Singleton Pattern.
The one you need to instatiate is Test. As i see there's no relation with Singleton pattern, don't you miss any code?

I Have a problem with understanding some Java code

The Code:
package com.keyoti.rapidSpell;
import java.util.Comparator;
// Referenced classes of package com.keyoti.rapidSpell:
// RapidSpellChecker
class RapidSpellChecker$CompareL
implements Comparator
{
public int compare(Object a, Object b)
{
return (int)(100D * (suggestionScore2b(topWord, (String)b) - suggestionScore2b(topWord, (String)a)));
}
public void with(String w)
{
topWord = w;
}
private String topWord;
RapidSpellChecker$CompareL()
{
}
}
This is the one the many classes in the application.
What does the $ sign in class RapidSpellChecker$CompareL implements Comparator signify?Is it simply the class name or has some significance?
I suspect this is decompiled code. (See at the bottom for more information.) The $ shows that it's a nested class within RapidSpellChecker. So the code would originally have looked something like this:
public class RapidSpellChecker
{
// Other code withing RapidSpellChecker
static class CompareL implements Comparator
{
// Code for compare, with etc
}
}
I've shown this as a static nested class, because the code you've shown doesn't have any implicit reference to an instance of RapidSpellChecker. If it did, the original code would have been like this:
public class RapidSpellChecker
{
// Other code withing RapidSpellChecker
class CompareL implements Comparator
{
// Code for compare, with etc
}
}
In this case it's an inner class.
See the Java tutorial on nested classes for more information.
EDIT: I originally thought this was invalid code; that you couldn't use $ in an identifier in Java to start with. It turns out I'm wrong. From the Java Language Specification, section 3.8:
The $ character should be used only in mechanically generated source code or, rarely, to access preexisting names on legacy systems.
So it's valid, just discouraged.
That's a nested class. When the Java compiler compiles a class with nested classes, it separates all of them in different .class files.
class A {
class B {
}
}
gives A.class and A$B.class
You can use $ in a variable name if you want. In a variable name it has no special significance.
$ is also typically used to indicate inner classes when you compile using javac
If you compile
class A {
class B {
}
}
You'll see A.class created and B.class.
For fun and amusement, you could create confusing looking "JQuery"-esque code in Java (you need the static import to use the $ static method). See the example below:
import static thisPackage.*;
public class $ {
public static $ $(String s) { return new $(s); }
public $ fadeIn(int fade) { return this; }
public $ slideUp(int slide) { return this; }
public $ delay(int ms) { return this; }
public $(String s) { }
public static void main(String[] args) {
$("#foo").slideUp(300).delay(800).fadeIn(400);
}
}
Implementing this with a DOM library underneath would be a fun project!

Categories