Getting relative inner class name in Java - java

package u.v;
class x {
static class xx {
static class xxx { }
}
}
While I can get the canonical ("absolute") name of the inner class
public class a{
public static void main(String[] args) {
System.out.println(x.xx.xxx.class.getCanonicalName()); //u.v.x.xx.xxx
}
}
and I can also get the last component of the class name
public static void main(String[] args) {
System.out.println(x.xx.xxx.class.getSimpleName()); //xxx
}
how would I go around elegantly getting a relative class name?
Utils.relativeClassName(x.xx.xxx.class, x.class); //xx.xxx

The following string manipulation should do the job:
xxx.class.getCanonicalName().substring(x.class.getCanonicalName().length + 1)
+1 is for . (dot) between the last outer class name and the name of interesting class.

You can use this function. The +1 is for the extra .
public static String getRelativeClassName(Class<?> inner, Class<?> outer) {
int length = outer.getCanonicalName().length();
return inner.getCanonicalName().substring(length+1);
}

Related

How do I create a proper Java instance?

I have created a public class helloworld and I am trying to create an object for class Abc. I have used "new" keyword to create an instance for Abc class.But still I am getting an error "non-static variable this cannot be referenced from a static context." in 4th line.
How do I solve this problem?
public class helloworld {
public static void main (String[] args)
{
Abc obj = new Abc();
}
class Abc
{
int i;
}
}
For simplicity, put class Abc in a different file and make it a public class.
helloworld.java
public class helloworld {
public static void main (String[] args)
{
Abc obj = new Abc();
}
}
Abc.java
public class Abc
{
int i;
}
Or you can declare your class Abc as static:
public class helloworld {
public static void main (String[] args)
{
Abc obj = new Abc();
}
static class Abc
{
int i;
}
}
When you create an inner class, it follows the same rule as members of a class: Static members of a class cannot directly access Instance members. Thus, you will need to declare Abc as a static class.
PS: please use CamelCasing conventions to name your classes. Ex: Use HelloWorld instead of helloworld.
Hope this helps!
First of all: Heed Jon's advise. That said, you can quickly solve this particular problem by changing your inner class into a static class:
static class Abc {
int i;
}
I know this might seem a bit weird, but you cannot refer to regular inner classes without first creating an instance of the outer class. Since the main method is static there is no instance of HelloWorld yet. This means it cannot refer to a regular (instance-bound) inner class only to a static inner class.
Arguably a better solution is to create an instance of your class first thing in your main method:
// class names should be camel case with an upper case first letter
public class HelloWorld {
public static void main (String[] args) {
HelloWorld app = new HelloWorld();
app.start();
}
// note that this is not a static method
private void start() {
Abc obj = new Abc();
}
private class Abc {
int i;
}
}
Abc is an inner class of helloworld. To instantiate it you need an instance of helloworld
Abc abc = new helloworld().new Abc();
or make Abc a static inner class.
static class Abc {}
The first awnser is correct but don't be easy. This is the easy way for a eclipse project o similar.
Create a ABC class:
public class Abc
{
int i;
}
Import in a Hello world class and declare static:
import Abc;
public class HelloWorld{
private static Abc abc=new Abc();
public static void main(String[] args){
//do something
}
}
All IDE that you use. Help you to import the class : )

Visibility of inner class variables

I have a code-
public class Hello
{
void create()
{
Inner obj=new Inner();
obj.r=100; //Able to access private variable x
obj.display(); //displays 100
}
class Inner
{
private int r=45;
void display()
{
System.out.println("r is : "+r);
}
}
public static void main(String[] args)
{
Hello ob=new Hello();
ob.create();
}
}
In the above code,by creating an instance of the inner class,we are able to access the private variable defined in that class.But this is not in the case of inheritance.Why it is so?For e.g.,in this code-
class One
{
private int x;
void getData()
{
x=10;
}
void display()
{
System.out.println("x is : "+x);
}
}
class Two extends One
{
int y;
void putData()
{
One o=new One();
o.x=13; //Error
}
}
public class File
{
public static void main(String[] args)
{
Two to=new Two();
to.putData();
}
}
What is the exact reason behind it?Thanks in advance...
See the Java Language Specification.
Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (ยง7.6) that encloses the declaration of the member or constructor.
Meaning that a top-level class can access the private members of it's nested classes.
Or said another way: Private means private to the top-level class and all it's nested classes, not private to the nested class itself.

java - can a class type parameter from a static main class be passed to another class

I have 2 classes the static main class and class B. I'm trying to pass main to B, where there is a method that sets fields.
Can this be done?
If so, could you please provide examples?
public static void main(String[] args) {
ArrayList a = new ArrayList()
class b = new class()
b.update(b);
}
class a {
public void update(ArrayList a) {
//updates the encapsulated arrayList field
}
}
The error message keeps on saying that one is static and the other is non-static, but they should be pointing the same object
I'm not entirely sure what you are trying to do, but here is an example that shows that you can pass an instance of the main class into another class:
public class A {
private String str = null;
public static void main(String[] args) {
A a = new A();
B b = new B(a);
System.out.println(a.getStr());
}
public String getStr() {
return this.str;
}
public void setStr(String str) {
this.str = str;
}
}
public class B {
public B(A a) {
a.setA("hello");
}
}
Running this code will print out hello.
main is static and public, so you can call it from any other class as any other public static method: statically.
if you have a class A that contains a
public static void main(String[] args)
method, then class B can call this method like
A.main(s);
where s is String[]
your question is far from clear, so I suggest you to add more code samples to make it clear what you're really trying to do.

Java: concerning nested classes

I have a few classes I need: Score, Course, and handicap. The file is "handicap.java", thus the main class is "handicap".
If I try and nest the Score class or the Course class inside of the "handicap" class, I receive this error upon trying to instantiate an instance of either class:
handicap.java:129: non-static variable this cannot be referenced from a static context
Score sc = new Score(score, course);
^
handicap.java:141: put(java.util.GregorianCalendar,Score) in java.util.Map<java.util.GregorianCalendar,Score> cannot be applied to (java.util.GregorianCalendar,handicap.Score)
g.scores.put(greg, sc);
If I add "static" to the Score class declaration, I still receive the second error. Help?
The Code is here: http://pastebin.com/CvT1SCvb
take a look on this
public class Handicap {
public class Score{
}
public static class ScoreStatic{
}
public static void main(String[] args) {
Handicap h = new Handicap();
h.method();
new Handicap.ScoreStatic();
}
public void method(){
new Handicap.Score();
}
}
By the looks of it , you are getting compilation error.
Please read about the Nested Classes : http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
This is the way it works :
public class handicap{
public static void main(String... args) {
handicap st = new handicap();
handicap.Score fl = st.new Score();
}
class Score{
//blah
}
}

Utilizing Public Final Classes Java

I would just like a clear example of how to instantiate a public final class in Java. I have to use a method from a class like this for a project, and have no idea how to instantiate it in the first place. Very difficult to find a clear example and explanation of the proper syntax. Thanks for the help.
public class Test {
public static void main(String[] args) {
Project pro = new Project();
pro.getName();
}
}
final class Project{
public String getName(){return "";}
}
===============================
A final class can be created like a normal class, Only thing is it can not be extended
This is an example
public class del {
public static void main(String args[])
{
x x1=new x();
System.out.println(x1.u());
}
}
final class x
{
public String u()
{
return "hi";
}
}
As you can see,x is a final class and have a method u which returns a string.
I am instatiating x in class del and calling its method u.
The output is hi
For more info click on final
final class Test{
public void callMe(){
System.out.println("In callMe method.");
}
}
public class TestingFinalClass{
public static void main(String[] args){
Test t1 = new Test();
t1.callMe();
}
}
Output : In callMe method.
final in java is applied to variable,method,class
final variable : the variable can not be signed with another value.
final method : the method cannot not be overridden.
final class : the class cannot extended.
The best example is String class in java. public final class String you can access the methods of String class as normal.
Some links
final keyword
String class
public class Test {
public static void main(String[] args) {
StdRandom stdRandom = StdRandom.getInstance(); /* this will retun an instance of the class, if needed you can use it */
int result =StdRandom.uniform(1);
System.out.println(result);
}
}
final class StdRandom{
private static StdRandom stdRandom = new StdRandom();
private StdRandom(){
}
public static StdRandom getInstance(){
return stdRandom;
}
public static int uniform(int N){
// Implement your logic here
return N;
}
}

Categories