Inner Nested Static Class cannot be called from another class - java

I have one class in a file named WeatherContract.java which has a static inner class, as follows:
public class WeatherContract {
...
...
public static final class WeatherEntry implements BaseColumns {
...
...
}
}
Now I am trying to call the inner class in another file called TestWeatherContract.java as follows
...
import com.example.android.sunshine.app.data.WeatherContract;
...
public class TestWeatherContract extends AndroidTestCase {
...
public void testBuildWeatherLocation() {
Uri locationUri = WeatherContract.WeatherEntry.buildWeatherLocation(TEST_WEATHER_LOCATION);
...
Now in the following line, the word "WeatherEntry" is marked in red and when I hover on the word I get the following error "Cannot resolve symbol 'WeatherEntry'.
Uri locationUri = WeatherContract.WeatherEntry.buildWeatherLocation(TEST_WEATHER_LOCATION);
Please note that I am not getting any error in the import statement, so I'm assuming that there are no errors in stating the path of the class.
Also, I have another file called FetchWeatherTask.java. I have the following import statement at the beginning of the file:
import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry;
In this case, in the import statement again the word "WeatherEntry" is marked in red and I get the error "Cannot resolve symbol 'WeatherEntry'".
Please help. I'm on Android Studio 1.5. I have posted this question earlier, but it was put on hold because I provided incomplete details. So I am posting it again with all details. I'm sorry if I have violated the rules of the community, I am new here. Thank you.

WeatherEntry is a class and not a member. To access methods of WeatherEntry you still need an instance of it. E.g.
WeatherContract.WeatherEntry.buildWeatherLocation(TEST_WEATHER_LOCATION);
should be
WeatherEntry weatherEntry = new WeatherContract.WeatherEntry();
weatherEntry.buildWeatherLocation(TEST_WEATHER_LOCATION);

Related

JSP could not find available java class

I used following code to call the java class from the JSP page.
<%String something=com.Package1.PrintInPicture.workingFunction(recentData);%>
I have package named as "com.Package1" as well as class and method named as "PrintInPicture" and "workingFunction(Stirng data)" respectively in that package. This is shown in code below:
package com.package1;
public class PrintInPicture {
static int width, height;
public static String workingFunction(String img_name) throws IOException{
}
But my JSP page is showing following error in the code which I have shown above:
cannot find symbol
symbol: class PrintInPicture
location: package com.Package1
Please, Help me to solve this error.

How to reference a class in a different package in the same project

I've tried working through some similar questions but I'm not getting anywhere
I have a main class in a package called overview.
In that class I create a string
I then want to send the string to another class in a different package in the same project
In my main class I have:
package Overview
import Bravo.*;
//some code
String s;
///Some code
Bravo.mane(s)
In the recipient class I have
package Bravo;
public class mane {
public mane(String s) {
// TODO Auto-generated constructor stub
}
}
When I am in the sending class main I seem to be able to access the class (in that when I type Bravo. (it gives me the class available in that package) but I still get an error saying that Bravo cannot be resolved ( in main).
Bravo.mane(s)
this is the place you are getting the error , you are calling the constructor of the class. you can't call the constructor. constructor will be invoked when you instantiate the object.
ex:-
mane maneObj = new mane("string");

Netbeans doesnt recognize class in the same package

i am creating a little game with libgdx framework and netbeans 8. I have all java classes in a single package that match with the directory structure.
The problem is that i cant import or isntantiate classes, for example:
package com.myfolder.folder2;
import ...
public class myclass1{
private myclass2 mc2;
etc...
}
In this case myclass2 is public and is inside the package but netbeans complains "cannot find symbol".
If i try with alt+enter, netbeans says "Create class myclass2 in package com.myfolder.folder2" or the same like an inner class. If i press the first option, netbeans create a class in the package with the file name myclass2_1 (becouse myclass2 exists!), and myclass1 doesnt recognize the new class.
If i try to import the class:
import com.myfolder.folder2.myclass2;
It gives me the same error, and in fact the code completion tool only gives me one crazy option in the import sentence:
import com.myfolder.folder2.myclass1;
Import the same class.
What can i do? I never have these problems using netbeans.
PD: Sorry for my english :)
You can use a class inside the same package like this:
ClassName classVariableName = new ClassName();
Then when you want to run something from the class you would put
classVariableName.MethodThatIWantToRun();
Or if you want to access a property from that method you would access it in a very similar way:
classVarabileName.PropertyIWantToAccess
Example:
You have one class with a property you want to access:
class MyClass {
public int MyProperty = 5;
}
You access it in this class:
public class MainClass {
public static void main(String[] args) {
MyClass myClass = new MyClass();
System.out.println(myClass.MyProperty);
}
}
If that doesn't work than you might have some other problem.
It was an error with one of my class package definition:
public class DesktopLauncher{
public static void main(String... args){
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
.
.
.
new LwjglApplication(new MyClass, config);
}
}
It was in MyClass, becouse i copied a snippet from an older project, and accidentally copied the older package.
NetBeans is not smart enough,
Solution: just declare the package name in all classes, example:
Class A:
package test;
public class ClassA {
public static void main(String[ ] args) {
ClassB.myFunctionB();
}
}
Class B:
package test;
public class ClassB {
public static void myFunctionB () {
System.out.print("I am ClassB!");
}
}

Error using classloader to load groovy class

I am attempting to load a groovy class by name using a classloader, and the class fails to load in the case that the class has a reference to a static inner class in another class.
Inside my groovy class I have the following:
def classLoader = getClass().classLoader
try {
classLoader.loadClass( "com.test.TestClass" )
} catch(Throwable e) {
Sigil.logger.error("Error loading class: $it >> ${e.message}", e)
}
In the above, my groovy file TestClass has a static inner class inside it, that extends a static inner class of another file. When I try to run the above code I get the message:
ERROR [05 Aug 2013 06:53:28,851] (invoke0:?) - Error loading class: com.test.TestClass >> startup failed:
unable to resolve class UserValidity.Validator
# line 85, column 5.
public static class Validator extends UserValidity.Validator{
^
1 error
Has anyone come across any problems dealing with static inner classes and class loading in groovy before? The classes all compile correctly and unit tests run etc. I would have thought that when I try to load the class TestClass explicitly in my classloader, it would also load the other necessary classes from the source tree as needed?
UPDATE:
Here is a snippet of the class that is failing to load:
class TestClass{
//... Other normal class stuff here
public static class Validator extends UserValidity.Validator
#Override
def validate(u) {
def result = super.validate(u)
if(!u.valid ){
result += [isValid:false]
}
result
}
}
}
And this fails as it says it cannot resolve the reference to the UserValidity.Validator, which is also pretty simple:
class UserValidity {
//normal class stuff here
public static class Validator {
def validate(u){
//do validation stuff
result
}
}
}
Both are just regular groovy classes.
UPDATE 2:
If I extract the static inner class UserValidity.Validator out in to a standalone class, and just extend that with the static inner class in TestClass then it appears to work, so definitely seems to be some issue with the parent of the inner class being another inner class

Java newbie problem: package with private access

Pack.java imports pack.TestPack; but it cannot access it. I cannot understand why it cannot access the class despite the import.
Error
Pack.java:7: TestPack() is not public in pack.TestPack; cannot be accessed from outside package
System.out.println(new TestPack().getHello());
^
1 error
Pack.java
import pack.TestPack;
import java.io.*;
public class Pack
{
public static void main(String[] args){
System.out.println(new TestPack().getHello());
}
}
TestPack.java
package pack;
import java.util.*;
import java.io.*;
public class TestPack
{
private String hello="if you see me, you ar inside class TestPack";
public String getHello(){return hello;}
TestPack(){}
}
You should make TestPack's constructor public.
public class TestPack
{
private String hello="if you see me, you ar inside class TestPack";
public String getHello(){return hello;}
public TestPack(){}
}
The thing is, even though TestPack visibility is public, its parameterless constructor visibility is package (which is the visibility when you don't specify one explicitly).
package visibility means that classes in the same package will be able to see it. Since TestPack and Pack are not in the same package, Pack can't call TestPack's constructor.
In the way you are using getHello function, you may start thinking using static methods
public class TestPack
{
private static String hello="if you see me, you ar inside class TestPack";
public static String getHello(){return hello;}
private TestPack(){}
}
then you just will do:
public class Pack
{
public static void main(String[] args){
System.out.println(TestPack.getHello());
}
}
I suggest that you don't make the class public but make the constructor public and have folks use a public interface that your class implements. It is a good idea to start the API to your package to be public interfaces (and perhaps some public abstract classes) and hide your implementation classes by not marking them as public so that you can change these over time. You can then provide a public factory methods in your package which instantiate your package private class and return them as the interface types. Here is an interface which is public:
package stackoverflow;
public interface Widget {
public void doWidgetWork(String work);
}
Here is the implementation which is "package private". The compiler wont let code outside of the same package import nor use this class at all:
package stackoverflow;
/*package*/ class WidgetHidden implements Widget {
public WidgetHidden(String configOptionA, String configOptionB){
// ...
}
public WidgetHidden(){
// ...
}
public void doWidgetWork(String work)[
// ...
}
}
notice there that the second occurrence of the word /package/ is a comment (it is not legal in java to use that word there) but many programmers use such a comment in that position to show people that it was not an accident that the class is not public; it signifies that the developer really intended that the class is deliberately "package private". To let people instantiate the class from outside of your package you provide a static factory class (else an instance factory class):
package stackoverflow;
public class WidgetFactory {
public static Widget newInstance( String configOptionA, String configOptionB) {
return new Widget( String configOptionA, String configOptionB);
}
}
The whole point of the factory class is that it hides your internal classes (the ones you hide as package private). Over time you can change your factory classes to return new classes or rename or delete the WidgetHidden class.
Many frameworks indicate which classes other developers should not use by putting them into a package with the name "internal" in it. The public interfaces would be in the main package (e.g. "com.stackoverflow.widget") and the hidden classes into your internal package which only exposes public factory classes (e.g. "com.stackoverflow.widget.internal").
A variation on the theme is to not use a static method on the factory class; make it a regular method. The alternatives are called "static factories" or "instance factories" depending on whether the method is static or not. Not making the method static seems like more work for people using your package as they first have to instantiate your factory object before using it to create Widget. Where is helpful is when people might want to set some defaults for all widgets on the constructor of the factory then use the none static newInstance methods to specify anything beyond the defaults:
public class WidgetInstanceFactory {
private String defaultOptionA = null;
public WidgetInstanceFactory( String defaultOptionA ) {
this.defaultOptionA = defaultOptionA;
}
public Widget newInstance( String optionB ) {
return new WidgetHidden( this.defaultOptionA, optionB );
}
}
It is possible to get around package private protection using reflection to find and invoke the constructor. A really nice feature of the Spring framework it that it will instantiate classes that are not public even when there is no factory class (although it is more polite to provide factory classes which Spring is happy to use also). The following code will work:
package stackoverflow.other;
class TestInstantiate {
private Widget myWidget = null;
public TestInstantiate(){
this.myWidget = instantiatePackagePrivateClass("stackoverflow.WidgetHidden");
}
private Widget instantiatePackagePrivateClass(String className)
throws ClassNotFoundException, NoSuchMethodException,
InstantiationException, IllegalAccessException,
InvocationTargetException {
#SuppressWarnings("unchecked")
Class<FileUploadSequence> clazz = (Class<Widget>) Class.forName(className);
Constructor<Widget> constructor = clazz.getConstructor(new Class[]{});
constructor.setAccessible(true);
Widget widget = (Widget) constructor.newInstance((Object[])null);
return widget;
}
}
In that example I used the no arguments constructor but clearly you can find and invoke the two string constructor using the same approach. Clearly such code gets around the intention of the programmer who wrote WidgetHidden; they wanted to hide it as they are likely to change it. Anyone who uses such a back door to manipulate the package private object should be aware that the class WidgetHidden is not part of the public API of the framework they are using so it likely to be deleted or changed without prior notice by the developer who wrote the package you are using. Renaming it to be WidgetInternal and putting it into an "internal" package make it every more the case you are telling people "do not uses". The JVM has optional security setting which prevent people from doing such tricks; but the person running the JVM has to configure it externally to dis-allow such tricks which is only useful when you want to run someone else code you don't trust and prevent it from pulling such tricks.
The book Effective Java by Josha Block 2nd Edition has a lot of discussion and examples and details of the pitfalls when trying to write a good API. It has a lot of detail to explain why you should always look to hide as many classes as you can with lots of other good "tricks of the trade".

Categories

Resources