Accessing to private classes on Java class - java

Suppose i have a class A:
class A
{
private String value;
private B field;
public C otherField;
}
class C
{
private String otherValue;
}
class B
{
private String name;
}
Now, if i do a A.class.getClasses(), ill get an array with one element (the one which is public, something that makes sense based on what javadoc of Class.java says).
My question is: is there a way to get return a list of public + private fields of a class?
Thanks

The getClasses() method is not the correct way to access the Fields that are part of the A class. You need to use the getDeclaredFields() method to access an array of Field objects representing the fields in the class. From there, you'll need to set the accessibility of the field to true with a call to setAccessible(). There is more information available by looking into the Java Reflection API as well as here

You should notice, that getDeclaredField will only return the fields of the class which are declared in the class. Fields which are inherited from a super class will not be returned. To get all fields of a class you have to iterate over the super classes (using Class.getSuperclass()).

Related

Is it possible to receive subclass's name in compile time in Java?

I'm trying to create a snacks machine implementation in java.
I have created an abstract class named Product that will give the basic design for each of the offered products.
I mean we have the abstract class Product and then other classes like Nachos, Cake, etc.. that inherita from Product.
Product class does not contain too much, it just contains the name , the price and the available amount of the product (these are the fields in the class).
It also has get methods for the fields that just return the value for each one.
The problem is that I want to set the name of the product as a static final because if a product's name is Nachos, it won't be changed. I mean it'll be possible to create more Nachos objects but the name of their class is still going to be Nachos.
So there is no reason to NOT to do that static final.
The issue with that is that i'm not sure how to set it correctly.
public abstract class Product {
private static final String productName = getClass().getSimpleName();
private int price;
private int amount;
....
Constructor..
Get methods..
I thought about getClass().getName() or getSimpleName() but it gives me an IDE error which indicates that the only way for me to also use that field as static final and also to use getClass is by writing Product.class.getName();.
The problem is that if i'll do that, the name that will be returned is Product and not Cake or Nachos or other sub classes.
If your Class has some attribute that describes that Class (e.g a product name), that's an attribute of that Class. You shouldn't write code that uses the name of the class itself with getClass().getName(), that's tying your business logic to implementation details, and there's no reason (or very few good reasons), why your code would need to know the name of the class itself.
Instead, add an attribute like productName to your class:
public class Product{
private String productName;
public Product(String name){
this.productName = name;
}
public String getProductName(){
return this.productName;
}
}
You should just use "final" and drop the "static". By declaring the variable as final you can assign the value of "getClass" that use "this" for reference. "this" doesn't work for static.
abstract class Product {
private final String productName = this.getClass().getSimpleName();
public String getProductName() {
return productName;
}
}
The "this" can be omitted in "this.getClass().getSimpleName()", leaving only "getClass().getSimpleName().
It doesn't make sense to use "static" because you would access the attribute directly via the class reference. But this would not work because to get the "getClass" you would need to be within some scope (constructor...) because the attribute is static, it is impossible to assign the value of the attribute at the time of its creation, making it impossible to use the " Final".
A static member belongs to the class in which it is defined. Declaring productName as static on the class Product means that every concrete implementation would have the same value. This is not what you want.
I think the solution that is closest to what you describe is not to have a member at all. Instead, declare an accessor as follows.
public abstract class Product {
public final String getProductName() {
return getClass().getSimpleName();
}
}
Thus, every instance of a given subclass (e.g. Taco) references the same Class object for its type. We never duplicate the value because we are accessing the singular value in our memory space. We declare this method to be final so that subclasses cannot override it. This enforces that the productName will always be the simpleName of the concrete implementation.

Different form of encapsulation

According to the OOP concepts, encapsulation is considered as defined private variables and public getter and setter methods.
Example:
public class Student {
private String name;
private int id;
public void setName(String name){
name = this.name;
}
public void setID(int Id){
id= this.id;
}
public String getName(){
return name;
}
public int getID(){
return id;
}
}
But if I wrote this code in the following way, could I say this class follows encapsulation concept ?
Because here, we return department name by using public method.
public class Student {
private department;
public String getDepartmentOfStudent(String name){
// write java code to get department name based on name from DB
return department;
}
}
Case II: If private variable department was not declared and just return value retrieved from DB, would we say that this class follows encapsulation?
But if I wrote this code in the following way, could I say this class follows encapsulation concept ?. Because here, we return department name by using public method.
=> Usually getter and setter are public. variables are private.
Case II : If private variable "department" was not declared and just return value retrieved from DB, would we say that this class follows encapsulation?.
=> Yes, its still encapsulation . It is not mandatory to have both getter and setter for every variable. So how you set data in variable, does not matter.
Encapsulation is defined as the wrapping up of data under a single
unit. It is the mechanism that binds together code and the data it
manipulates.Other way to think about encapsulation is, it is a
protective shield that prevents the data from being accessed by the
code outside this shield.
1 - Technically in encapsulation, the variables or data of a class is
hidden from any other class and can be accessed only through any
member function of own class in which they are declared.
2 - As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
3 - Encapsulation can be achieved by: Declaring all the variables in the class as private and writing public methods in the class to set
and get the values of variables.
Source:- https://www.geeksforgeeks.org/encapsulation-in-java/
For both cases, the answer is also "Yes". It is because your private field variable is not being accessed directly by other classes (e.g. declaring it as public String department). Accessible department is still being controlled by the code path of public String getDepartmentOfStudent(String name) which is playing the role of a public getter.
Getter gets it's names due to it's functionality that it returns some private attributes not by it's name. For example: getName() or getAge().
If a method named abc() returns some private data member/attribute then it is a getter method.
Yes your code follows encapsulation. In encapsulation the variables of the object cannot be directly accessed and modified by any other object.
In Case II:
If private variable "department" was not declared and there is no other public variables in your class, then yes you have encapsulation as the class's variables or data cannot directly accessed by another class.
To answer both questions we need take into account the concept of encapsulation
The localization of knowledge within a module. Because objects
encapsulate data and implementation, the user of an object can view
the object as a black box that provides services. Instance variables
and methods can be added, deleted, or changed, but as long as the
services provided by the object remain the same, code that uses the
object can continue to use it without being rewritten. (...)
So, we can say YES, it does; because to the client consuming the information provided by Student there is no knowledge of how the value of department is being retrieved/handled and returned, it just knows that from the call to getDepartmentOfStudent will be a String result. It actually doesn't care whether it is comming from database or memory, only Student knows that.

Java Annotation Processing how to check if VariableElement is a primitive type(int, float) or an object some class

I have a class
public class SomeClass {
#CustomAnnotation1
String stringProperty = "LALALA";
#CustomAnnotation1
int integerProperty;
#CustomAnnotation1
ClassObject classObject;
}
CustomAnnotation1 is a custom annotation defined by me which can be put over any Field. Suppose class ClassObject is something like
public class ClassObject {
#CustomAnnotation1
public String someOtherString;
public String log;
}
What I want to achieve - If my annotation is put on any field which is not a primitive type, I want to access all the fields of that class.
My Approach - Get all the fields annotated with CustomAnnotation1, iterate over all of them and if it is non-primitive, get all the fields inside that class and process.
What I've tried - I am able to get all the elements annotated with my annotation using the below code in my AbstractProcessor class.
Collection<? extends Element> annotatedElements = roundEnvironment.getElementsAnnotatedWith(CustomAnnotation1.class);
List<VariableElement> variableElements = ElementFilter.fieldsIn(annotatedElements);
Questions -
I've researched a lot about the VariableElement class but unable to find a way to check if the field is primitive or not. Can this be done?
Is there any better approach to achieve this?
VariableElement.asType().getKind().isPrimitive()

Access Modifiers in Java when used with Immutable Class [duplicate]

This question already has answers here:
Immutable Type: public final fields vs. getter
(9 answers)
Closed 6 years ago.
Is it recommended to have public access modifiers for the data fields in final (Immutable) java class, even if the data fields are not the references to mutable datatype Or Shall we access data fields directly as data fields are supposed to be defined in constructor itself hence nullify all chances of changing the internal representation of class.
Please suggest?
For example:
public class MainApp {
public static void main(String args[]) {
Immutablesample immutablesample = Immutablesample.getInstance("akkhil");
System.out.println(" Before modification " + immutablesample.getName());
immutablesample.name = "gupta";
System.out.println(" After modification " + immutablesample.getName());
}
}
is the calling code trying to change the data field by accessing it directly(without access modifier) for the following class:
public final class Immutablesample {
private final String name;
private Immutablesample(String name){
this.name = name;
}
public String getName(){
return name;
}
public static Immutablesample getInstance(String name){
return new Immutablesample(name);
}
}
How would it make the class prone to get its internal representation changed if i change the modifier from private to public
private String name; to public String name;
since the object was creating with parameterized constructor so has immutable data fields, than why is it necessary to make data fields private?
Two simple rules to follow:
Try to make your whole class as "immutable" as you can. For example setting private final fields only via constructors. And when using "incoming" collection objects, consider to create a copy of their content to be really on the safe side.
Keep in mind that good OO is about exposing behavior; not about exposing data. Meaning: you absolutely do not want to make fields public unless you have really good reasons to do so. In other words: you do not want that some other class B does something because of the content of some field in class A. And the way to prevent that: making your fields private!
In general, it's a bad decision to show your inner presentation of a class, so it's much better if you hide even final immutable fields. You can only show such as fields if your class it's something like a tuple, where all members are used from outside.

How can I obtain a propery value inside an inherited Method in a Generic Class?

I'm writting a code like below, and I need to obtain a value of a child class from a static method of the parent class.
Can someone help me to solve it? Thank's in advanced.
public abstract class DataObject<T>{
public static int GetAllTotal(){
// How can I obtain a T propery called "code" = "001".
int cont = SQL.getTotalFromQuery(
"SELECT * from tblProducts where code = '001'"
);
return ffff
}
...
}
public class Product extends DataObject<Product>{
private String code = "001";
public Product(){
}
}
...
Product.GetAllTotal();
you need to use the following:
super.GetAllTotal();
In the child (derived) class.
Where super is the reference of the parent of a derived class in java.
First of all, you will need an object of the class to be able to access members dynamically from a static method.
Then you could define a public getCode() function in the parent that you override in the child class that returns the value of the code member variable.
use the keyword super to access the reference of the parent class. In your case,
super.GetAllTotal();
cant we make the GetAllTotal method parameterized to accept an argument, or their is some restriction in changing method definition
GetAllTotal(String code)

Categories