jMockit's access to a private class - java

I have a public class with a private class inside it:
public class Out
{
private class In
{
public String afterLogic;
public In(String parameter)
{
this.afterLogic = parameter+"!";
}
}
}
And wanted to test the In class with jMockit. Something along these lines:
#Test
public void OutInTest()
{
Out outer = new Out();
Object ob = Deencapsulation.newInnerInstance("In", outer); //LINE X
}
The problema is, in LINE X, when trying to cast ob to In, the In class is not recognized.
Any idea how to solve this?
Thanks!

The only constructor in class In takes a String argument. Therefore, you need to pass the argument value:
Object ob = Deencapsulation.newInnerInstance("In", outer, "test");

As suggested in the comment one way is to change the access modifier of the inner class from private to public.
Second way (in case you don't want to make your inner class public), you can test the public method of outer class which is actually calling the inner class methods.

Change the scope of the inner class to default then make sure that the test is in the same package.

There are two approaches, first as mentioned in other posts to change the scope to public. The second which I support is, to avoid testing private class altogether. Since the tests should be written against testable code or methods of the class and not against default behavior.

Related

How can i access one class variable into other

There are to separate classes class One and class Two. Both of classes are in same package. I want to access one class data into other class how can i access variable data. My program is very lengthy ,I just want the logic of this.Thanking you in advance.
Class A.java
public class A
{
public static void main(String ar[])
{
int a=100;
}
}
Class B.java
public class B extends A
{
public static void main(String m[])
{
A obj=new A();
System.out.println("Variable of class A is :"+ obj.a);
}
}
I have done this thing to get access like i declared variable a as Static so that i can directly get access but it's not working. and when i am compiling B.java It giving me error
cannot find symbol at := System.out.println("Variable of class A is :"+ obj.a);
And
Illegal start of expression (when i am delaring variable a as public)
:-(error)public int a=100; [in class A].
Why are you using the static main method? Besides that the field a is local and not accessible outside the scope. Use this instead.
public class A
{
public int a;
public A()
{
a=100;
}
}
You don't have two true object-oriented classes above, but rather little more than two receptacles for static main methods. To combine code from two classes well, you will want to scrap that code and make OOP-compliant classes, complete with instance fields and methods. For more on this, check out the OOP section of the Java tutorials: link to OOP tutorial.
First, get rid of main() in A. You only want one main() in your application, and it's in B (since the one in A doesn't actually do anything):
public class A {
}
Now, you want A to have a class-level int value:
public class A {
private int a;
}
And you want it to have a default value of 100, yes? A constructor is a good place to do that:
public class A {
private int a;
public A() {
this.a = 100;
}
}
Now any time you do this:
A obj = new A();
you will have an object with a value. In order to access that value from outside that object, you need a "getter":
public class A {
private int a;
public A() {
this.a = 100;
}
public int get_a() {
return this.a;
}
}
Now in B (or anywhere, really), you can create an instance of A and access that value by using the "getter":
A obj=new A();
System.out.println("Variable of class A is :"+ obj.get_a());
Semantically, don't think of it as "accessing a variable from another class". Instead, think of what your objects are and what they represent. If it were a physical, real-world object which internally contained some kind of value.
When you create an instance of that object, the instance would internally have that value somewhere. From the outside of that object, it doesn't really matter how that value is internally maintained. There just needs to be some kind of interface to see the value. Which is what the "getter" method does.
One-liner answer: To access a variable outside a class, make it class-level. You have written a method-level variable that's accessible only inside that scope (method).
To elaborate:
There are to separate classes class One and class Two. Both of classes are in same package. I want to access one class data into other class how can i access variable data.
So basically you know that to by extending, you should be able to access parent class data into your subclass. For that, simply make the data in your parent class as class level.
class A {
int var = 10; //class level, but non-static, so to access you need A object
void method() {
int var = 20; //this is method local and can not be accessed outside
}
}
public class B extends A {
public static void main(String[] args) {
A aObj = new A();
System.out.println(aObj.var);
}
}
Illegal start of expression (when i am delaring variable a as public)
Its illegal. Because access modifiers like public, private etc. are applicable to class-level stuff like the first var or the main method in class B you see.
Said that:
You need to immediately go here: https://docs.oracle.com/javase/tutorial/
rather than just trying to run some classes when you lack language basics.

Can I access an outer class instance from an instance of that outer classes inner class anonymously? [duplicate]

Say if I have a dropdown in a form and I have another nested class inside of this class .
Now what's the best way to access this dropdown from the nested class?
Unlike Java, a nested class isn't a special "inner class" so you'd need to pass a reference. Raymond Chen has an example describing the differences here : C# nested classes are like C++ nested classes, not Java inner classes.
Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference.
// C#
class OuterClass
{
string s;
// ...
class InnerClass
{
OuterClass o_;
public InnerClass(OuterClass o) { o_ = o; }
public string GetOuterString() { return o_.s; }
}
void SomeFunction() {
InnerClass i = new InnerClass(this);
i.GetOuterString();
}
}
Note that the InnerClass can access the "s" of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the "string s;" is private because no other access permission was specified.
Nested types aren't like inner classes in Java - there's no inherent instance of the containing type. (They're more like static nested classes in Java.) They're effectively separate classes, with two distinctions:
If the containing type is generic, the nested type is effectively parameterised by the containing type, e.g. Outer<int>.Nested isn't the same as Outer<string>.Nested.
Nested types have access to private members in the containing type.
Unlike Java, in C# there is no implicit reference to an instance of the enclosing class.
You need to pass such a reference to the nested class. A typical way to do this is through the nested class's constructor.
public partial class Form1 : Form
{
private Nested m_Nested;
public Form1()
{
InitializeComponent();
m_Nested = new Nested(this);
m_Nested.Test();
}
private class Nested
{
private Form1 m_Parent;
protected Form1 Parent
{
get
{
return m_Parent;
}
}
public Nested(Form1 parent)
{
m_Parent = parent;
}
public void Test()
{
this.Parent.textBox1.Text = "Testing access to parent Form's control";
}
}
}
Static Members
Since no one has mentioned it so far: Depending on your situation, if the member variable can also be static, you could simply access it in following way.
class OuterClass
{
private static int memberVar;
class NestedClass
{
void SomeFunction() { OuterClass.memberVar = 42; }
}
}
Sidenote: I marked memberVar purposefully (and redundantly) as private to illustrate the given ability of the nested class to access private members of it's outer class.
Caution / Please consider
In some situations this might be the easiest way/workaround to get access, but ...
Static also means, that the variable will be shared across all instance objects, with all the downsides/consequences there are (thread-safety, etc.)
Static also means, that this will obviously not work if you have more than one instance of the parent's class and the variable should hold an individual value for each instance
So in most cases you might wanna go with a different approach ...
Passing a Reference
As most people have suggested (and because it is also the most correct answer), here an example of passing a reference to the outer class' instance.
class OuterClass
{
private int memberVar;
private NestedClass n;
OuterClass() { n = new NestedClass(this); }
class NestedClass
{
private OuterClass parent;
NestedClass(OuterClass p) { parent = p; }
SomeFunction() { parent.memberVar = 42; }
}
}
One other method, which is useful under certain circumstances, is to derive the nested class off of the outer class. Like so:
class Outer()
{
protected int outerVar;
class Nested() : Outer
{
//can access outerVar here, without the need for a
// reference variable (or the associated dot notation).
}
}
I have used this technique especially in the context of Structured Unit Tests. (This may not apply to the OP's particular question, but it can be helpful with nested classes in general, as in the case of this "duplicate" question: " Can i access outer class objects in inner class ")
You could pass the enclosing class as a parameter to the nested class constructor, like this:
private NestedClass _nestedClass;
public ParentClass()
{
_nestedClass = new NestedClass(this);
}
Nested classes are generally not recommended and should be private and/or internal. They are, in my opinion, useful sometimes though.
Correct me if I am wrong, you are trying to process the outer control from inner class hence you ran into this. A better way of doing this would be to handle affairs in a event driven fashion. Use an Observer pattern, Register a listener on the outer control (your nested/inner class will be the listener). Makes life simpler. I am afraid that this is not the answer you were expecting!
send the master class as an constructor parameter to the nested (inner) class.
there is a good answer above but I like to write sth.
c# nested class is by default private
private to containing class if your want to use it must be public

Access private inner class, through a public outer class - from another class

I am completely stuck on this and have been playing around with it for a while. I have a class "launcher", from which I want to access an instance of a private inner class "PropertyInstance", through the outer class "PropertyManager".
So, in my launcher I would like to write:
PropertyManager pm = new PropertyManager();
PropertyInstance pi = pm.getInstance("brickbreaker.properties");
In my PropertyManager class I have written the following code:
public PropertyInstance getInstance(String location)
{
PropertyInstance pi = null;
if(!propertyList.contains(location))
{
System.out.println("it does not contain it yet, so we will create it");
pi = new PropertyInstance(location);
propertyList.add(pi);
}
return pi;
}
And inside this class, I have the following inner class:
private class PropertyInstance
{
}
Which is irrelevant apart from the private modifier.
The problem is that I can not access the PropertyInstance class from my Launcher due to it being private, and I do not seem able to find a workaround so really any help is appreciated. If it can even be done.
EDIT: It seems to be unclear that I'm looking for a workaround whilst keeping the inner class private, sorry for the confusion! :)
Make an interface that defines the public access you want to your private class, make your private class implement it, and return it as that.
The workaround is to make it public.

How to test that a type declared as "public class" is a class using java.lang.Class?

java.lang.Class has methods to test if a given type is:
isAnnotation
isArray
isEnum
isInterface
isPrimitive
but how does one test that an object of type Class (instanceof Class is true) represents a declared, non-abstract class rather than in interface, enum, primitive, array, etc. For example:
package org.acme;
public class ACME {
public ACME() {
}
public static void main(String[] args) {
Class clazz = Class.forName("org.acme.ACME");
// Expected I could use a clazz.isClass().
}
}
I was looking for a isClass method, but there isn't.
Update
I see the confusion generated by my question - while some people got my question.
I did some further research and found out that in .NET
http://msdn.microsoft.com/en-us/library/system.type.isclass.aspx,
there this is a isClass member and I was looking for a similar method in java.lang.Class.
I now know that the equivalent in Java is to test for all the other isXXX methods to find out that it's not a class.
It seems there's a disconnect in your question. Everything is a class (except primitives - the isPrimitive() method actually means the class is an autobox type).
Class clazz = Class.forName("org.acme.ACME");
// Expected I could use a clazz.isClass().
That would be redundant. You already know it's a class. Because you have an instance of Class.
It would appear that for some reason you would like to know it's not any of the types of classes the methods you list tell you, in which case you'd simply do a check to negate those options:
if (!clazz.isAnnotation() &&
!clazz.isArray() /* && ... etc */ )
{
// Not any of those things.
}
Class objects are singletons. Therefore, if you have an instance of any type, you can test that it is an exact class instance using:
theInstance.getClass() == TheTargetClass.class
As to testing whether a class is a "full" class, just negate all the test you mentioned. This first test is already an efficient filter... And do not forget .isSynthetic().
Not so readable but
object.getClass().getModifiers() < 30 //abstract classes are not included
or in a more readable way:
object.getClass().getModifiers() < Modifier.PROTECTED + Modifier.STATIC + Modifier.FINAL
seems to work, being more neat (but more obscure) than
!(!isInterface() && !isEnum() && !is ...)
A simple class can only have these modifiers:
public static final int PUBLIC = 0x00000001;
public static final int PRIVATE = 0x00000002;
public static final int PROTECTED = 0x00000004;
public static final int STATIC = 0x00000008;
public static final int FINAL = 0x00000010;
while abstract, interafce, enum or annotation has larger values (over 200).
You can see the Modifiers of a class by calling Modifier.toString(myClass.getModifiers()). The getModifiers() class returns the sum in hexa of all modifiers (as I have tested on some values; the implementation is native).
A partial solution:
You can try to execute the Class's newInstance method. If the class is abstract or an interface an InstantiationException will be thrown- Otherwise, you're good.
The problem is that creating a new instance in a class you don't know might have unknown effects, or the class might not have a default constructor.
Two options that should work for you:
You can do class instanceof Object
You can check all the other is...() methods. If they are all false you have a class.

Can't access public non-static class attribute from secondary class

I have the following two classes:
public class Class1
{
public Class1 randomvariable; // Variable declared
public static void main(String[] args)
{
randomvariable = new Class1(); // Variable initialized
}
}
public class Class2
{
public static void ranMethod()
{
randomvariable.getSomething(); // I can't access the member "randomvariable" here even though it's public and it's in the same project?
}
}
I am very certain that it's a very fundamental thing I'm missing here, but what am I actually missing? The Class1 member "randomvariable" is public and so is the class and both classes are in the same project.
What do I have to do to fix this problem?
There are two problems:
Firstly, you're trying to assign a value to randomvariable from main, without there being an instance of Class1. This would be okay in an instance method, as randomvariable would be implicitly this.randomvariable - but this is a static method.
Secondly, you're trying to read the value from Class2.ranMethod, again without there being an instance of Class1 involved.
It's important that you understand what an instance variable is. It's a value associated with a particular instance of a class. So if you had a class called Person, you might have a variable called name. Now in Class2.ranMethod, you'd effectively be writing:
name.getSomething();
That makes no sense - firstly there's nothing associating this code with Person at all, and secondly it doesn't say which person is involved.
Likewise within the main method - there's no instance, so you haven't got the context.
Here's an alternative program which does work, so you can see the difference:
public class Person {
// In real code you should almost *never* have public variables
// like this. It would normally be private, and you'd expose
// a public getName() method. It might be final, too, with the value
// assigned in the constructor.
public String name;
public static void main(String[] args) {
Person x = new Person();
x.name = "Fred";
PersonPresenter.displayPerson(x);
}
}
class PersonPresenter {
// In a real system this would probably be an instance method
public static void displayPerson(Person person) {
System.out.println("I present to you: " + person.name);
}
}
As you can tell by the comments, this still isn't ideal code - but I wanted to stay fairly close to your original code.
However, this now works: main is trying to set the value of an instance variable for a particular instance, and likewise presentPerson is given a reference to an instance as a parameter, so it can find out the value of the name variable for that instance.
When you try to access randomvariable you have to specify where it lives. Since its a non-static class field, you need an instance of Class1 in order to have a randomvariable. For instance:
Class1 randomclass;
randomclass.randomvariable.getSomething();
If it were a static field instead, meaning that only one exists per class instead of one per instance, you could access it with the class name:
Class1.randomvariable.getSomething();

Categories