Internet Windows Android

What access modifiers are there in java. Access modifiers

Here we will try to cover almost all cases of using access modifiers. The only exceptions are their use for nested ( nested) and internal ( inner) classes, as well as for interfaces, since we have not yet considered these topics.

Classes and packages used in conjunction with access modifiers serve as encapsulation means, that is, a means of hiding implementation details behind a simple interface.

Access modifiers can be applied to both classes and their members - fields and methods. In total, there are four access modifiers and here we will give a brief description of them, then we will consider each in detail.

  • public- any component declared as public, accessible from any code
  • protected- allows access to the component within the package and classes of descendants
  • private- allows access to components within the class
  • default(no keyword) - allows access to components within the package

Inherited classes are classes inherited from a class. We haven't studied inheritance yet.

Access to classes

By default, top-level classes are available in the package in which they are defined.... However, if the top-level class is declared as public then it is available everywhere (or wherever the package itself is available). We have limited this statement to top-level classes because classes can be declared as members of other classes. Since these inner classes are members of the class, they obey the rules for controlling access to class members..

Accessing class members

The members of the class are always available inside the body of the class. Default class members are also available in the package in which the class is defined.

Public modifier

For a class that is not nested, only one of two possible access levels can be specified: given default and public . When the class is declared as public, it should be the only one public the class declared in the file and the file name must match the class name.

How public classes, fields, methods and constructors can be declared.

Protected modifier

We'll take a closer look at this modifier in the topic of class inheritance. If inheritance is not used, then this modifier works, just like the default modifier.

The only thing that can be briefly said now is that the components declared as protected will have access any child class from any package or any class from the same package.

How protected fields, methods, constructors, nested classes, and nested interfaces can be declared.

protected .

Private modifier

This is the most restrictive modifier in terms of access restriction. Items declared as private are accessible only within the same class and to no one outside the class.

How private fields, methods, constructors, nested classes and nested interfaces can be declared.

Top-level classes and interfaces cannot be declared as private .

Basically, access modifiers are a simple topic, but we'll come back to them later. While it was just an acquaintance. And now a little practice ...

I created classes Mod02.java, DefMod.java, ProMod.java and PrvMod.java which belong to the pro.java.pkg002 package, as well as the PubMod.java class, which belongs to the pro.java.pkg003 package. Next, I will give just screenshots of these classes and the result of the program:

We will talk about modifiers: what are modifiers, scopes, modifiers for classes, fields, methods. I think it won't be boring.

Modifiers in Java Are keywords that give a class, class field, or method specific properties.

To indicate the visibility of a class of its methods and fields, there are 4 access modifiers:

  • private the members of the class are only accessible within the class;
  • package-private or default (default) class members are visible inside the package;
  • protected class members are available inside the package and in derived classes;
  • public class members are available to everyone.

If you remember, at the end, when we already imported the Cat class, we still had a compilation error.

The thing is that we have not registered any access modifiers to our fields and methods, and they have a default property (class members are visible inside the package). To fix the compilation error for our code and finally run it, we need to make our constructor and methods public. Then they can be called from other packages.

You may start to wonder: what is all this for? Why not make the code visible from any package or class, but need to differentiate access? These questions will disappear on their own when the time comes to write complex and cumbersome projects. Now, when we write applications whose functionality is limited to one or two classes, it seems that there is no sense in limiting something.

Imagine that you have a class that displays a product object. For example a car. The car may have a price. You have created a price field and many other fields, a bunch of methods that are responsible for the functionality. Everything seems to be good. Your class car is part of a huge project and everyone is happy. But let's say that someone, by mistake or on purpose, instantiated the car class and set a negative price. How can a product have a negative price? This is a very primitive example and is unlikely to happen in real life, but I think the idea is clear. Sometimes you need to give access not directly, but through certain methods. It may be that the code is responsible for the functionality of other code, and you do not want someone to change and edit part of yours. For this all, there is an access restriction.

Constructors, methods and fields can have any access modifier. A class can only be either public or default, and there can be only one public class in one file.

For now, there will be enough about access modifiers. In the article "Object Oriented Programming" we will talk about them in more detail, but now let's talk about other modifiers of which, by the way, there are a lot.

Now the next modifier is static... It can be used in front of a method, field, or even a class when we want to declare a nested class. In Java, you can write classes inside other classes, and if the modifier before the class inside the class is static, then such a class is called nested, if there is another modifier or by default, then such a class is called internal. There will be a separate article about nested and inner classes, since everything is not so simple there.

The static modifier in front of a method or field indicates that they do not belong to an instance of this class. What does this mean for us? When we have described a class field or method as static, it can be called without using an instance of the class. That is, instead of this construction: Cat cat = new Cat (); cat.method (), you can just write Cat.method (). Provided that the method is declared static. Static variables are the same for all objects of the class. They have one link.

    public class Modificators (

    static int anotherStaticField = 5;

    public static void myStaticMethod () (

    someField = "My field";

    // nonStaticField = ""; compilation error

    // non-static fields cannot be used

    // in static methods

    public void myNonStaticMethod () (

    anotherStaticField = 4; // static fields can be used

    // in non-static methods

    // main method also has a static modifier

    new Modificators () .myNonStaticMethod ();

    Modificators.myStaticMethod (); // call static methods and fields

    // via classname.method

Another important thing to note about static modifiers is that static fields are initialized at class load time. Often in various kinds of Java tests, you can find the following code:

Question: what will be displayed on the console? It should be remembered that the static block will be displayed first in any scenario. Next will be the default block. Next, look at the console screen:

The next modifier we'll look at will be final.

I think the word final speaks for itself. By applying the final modifier, you say that fields cannot be changed, methods are overridden, and classes cannot be inherited (there will be a separate article on inheritance). This modifier only applies to classes, methods, and variables (also to local variables).

We will talk about the final modifier to methods and classes in the OOP article.

Next, there will be modifiers that will not be very clear for beginners or those who read this series of articles from scratch. And although I still cannot explain everything to you (due to the fact that you do not know the accompanying material), I still advise you to just familiarize yourself with them. When it comes time to use these modifiers, you will already understand most of the terms used below.

Modifier synchronized- indicates that the method can be used by only one thread at a time. While this may not tell you anything, the usefulness of this modifier will be seen as we learn about multithreading.

Modifier transient- says that some field should be ignored during object serialization. Typically, these fields store intermediate values.

Modifier volatile- used for multithreading. When a field with the volatile modifier will be used and changed by multiple threads, this modifier ensures that the field will change in turn and there will be no confusion with it.

Modifier native before the method declaration indicates that the method is written in another programming language. Usually in C.

Modifier strictfp- Provides performance of operations on numbers of type float and double (floating point) according to the IEEE 754 standard. Or, more simply, guarantees that within a method the results of calculations will be the same on all platforms.

I haven't talked about the modifier yet abstract... I will tell you about it briefly, because without knowledge of the basics of object-oriented programming, I see no point in talking about it.

A class that has the abstract modifier cannot be instantiated. The only purpose for it is to be expanded. An abstract class can contain both abstract methods as well as ordinary ones.

We will talk more about the abstract modifier in the OOP article.

This concludes the article on modifiers. Much has not been said about them. But this is due to the fact that we do not have OOP concepts yet. In a few more articles, we will add knowledge about modifiers and fill in the blanks.

Which you add at initialization to change values. The Java language has a wide range of modifiers, the main ones are:

  • access modifiers;
  • class, method, variable, and stream modifiers not used for access.

To use a modifier in Java, you need to include its keyword in the definition of a class, method, or variable. The modifier must be in front of the rest of the statement, as shown in the following examples:

Public class className (// ...) private boolean myFlag; static final double weeks = 9.5; protected static final int BOXWIDTH = 42; public static void main (String arguments) (// method body)

Access modifiers

Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. There are four access points:

  • Visible in package (default and no modifier required).
  • Visible only for the class (private).
  • Visible to all (public).
  • Visible to the package and all subclasses (protected).

The default access modifier is no keyword

Default access modifier- means that we do not explicitly declare an access modifier in Java for a class, field, method, etc.

A variable or method declared without an access control modifier is available to any other class in the same package. Fields in an interface are implicitly public, static, final, and methods in an interface are public by default.

Example

Variables and methods can be declared in Java without any modifiers, as shown in the following example:

String version = "1.5.1"; boolean processOrder () (return true;)

The private access modifier

Private modifier- methods, variables and constructors that are declared private in Java can only be accessed within the declared class itself.

The private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables declared as private can be accessed outside the class if the receiving public methods are present in the class (see below for an example and explanation).

Using the private modifier in Java is the main way to hide data.

Example

The following class uses private access control:

Public class Logger (private String format; public String getFormat () (return this.format;) public void setFormat (String format) (this.format = format;))

Here variable format class Logger is private, so there is no way for other classes to get and set its value directly.

Thus, to make this variable available to everything, we have defined two public methods: getFormat () which returns the value format, and setFormat (String) which sets its value.

Public access modifier

Public modifier- class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java universe.

However, if we try to access a public class in another package, then the public class has to be imported.

Due to class inheritance, in Java all public methods and variables of a class are inherited by its subclasses.

Example

The following function uses public access control:

Public static void main (String arguments) (// ...)

Method main () must be public. Otherwise, it cannot be called by the java interpreter to run the class.

Protected access modifier

Protected modifier- variables, methods and constructors that are declared protected in a superclass can only be accessed by subclasses in another package or for any class in a protected class package.

The protected access modifier in Java cannot be applied to class and interfaces. Methods and fields can be declared protected, however methods and fields in an interface cannot be declared protected.

Protected access gives a subclass the ability to use a helper method or variable, preventing an unrelated class from trying to use it.

Example

The following parent class uses protected access controls so that its child class overrides the method openSpeaker ():

Class AudioPlayer (protected boolean openSpeaker (Speaker sp) (// implementation details)) class StreamingAudioPlayer (boolean openSpeaker (Speaker sp) (// implementation details))

Moreover, if we define a method openSpeaker () as protected, then it will not be accessible from any other class other than AudioPlayer. If we define it as public, then it will become available to everyone. But our intention is to expose this method only to the subclass, which is why we used the protected modifier.

Access control and inheritance rules

The following rules in Java apply for inherited methods:

  • Methods declared public in a superclass must also be public in all subclasses.
  • Methods that are declared protected in a superclass must either be protected or public in their subclasses; they cannot be private.
  • Methods that are declared private are not inherited for everyone, so there is no rule for them.

Class, method, variable, and stream modifiers not used for access

Java provides a number of modifiers not for access, but for implementing many other functionality:

  • modifier static used to create methods and class variables;
  • modifier final used to complete the implementation of classes, methods and variables;
  • modifier abstract required for creating abstract classes and methods;
  • modifiers synchronized and volatile used in Java for streams.

Static modifier

Static modifier- used to create methods and class variables.

Static variables

The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of a static variable in Java exists, regardless of the number of instances of the class.

Static variables are also known as class variables. In Java, local variables cannot be declared static.

Static methods

The static keyword is used to create methods that will exist independently of any instances created for the class.

In Java, static methods or static methods do not use any instance variables of any class object, they are defined. The static methods take all data from parameters and some of these parameters are evaluated without reference to variables.

Variables and methods of a class can be accessed using the class name followed by a period and the name of the variable or method.

Example

The static modifier in Java is used to create class methods and variables, as shown in the following example:

Public class InstanceCounter (private static int numInstances = 0; protected static int getCount () (return numInstances;) private static void addInstance () (numInstances ++;) InstanceCounter () (InstanceCounter.addInstance ();) public static void main (String arguments ) (System.out.println ("Since" + InstanceCounter.getCount () + "instance"); for (int i = 0; i

You will get the following output:

Starting from 0 instance Created 500 instances

Final modifier

Final modifier- used to complete the implementation of classes, methods and variables.

Final variables

A final variable can only be initialized once. A reference variable declared final can never be assigned to refer to another object.

However, the data inside the object can be changed. Thus, the state of the object can be changed, but not the reference.

With variables in Java, the final modifier is often used with static to make a class variable a constant.

Example

public class Test (final int value = 10; // Below are examples of constant declarations: public static final int BOXWIDTH = 6; static final String TITLE = "(! LANG: Manager"; public void changeValue(){ value = 12; //будет получена ошибка } } !}

Final methods

The final method cannot be overridden by any subclass. As mentioned earlier, in Java, the final modifier prevents a method from being changed in the subclass.

The main intent to make the method final is that the content of the method should not be changed to the side.

Example

The declaration of a method using the final modifier in a class declaration is shown in the following example:

Public class Test (public final void changeName () (// method body))

Final class

The main purpose in Java of using a class declared as final is to prevent the class from being subclassed. If a class is marked final, then no class can inherit any function from the final class.

Example

public final class Test (// class body)

Abstract modifier

Abstract modifier- used to create abstract classes and methods.

Abstract class

The abstract class cannot instantiate. If a class is declared abstract, then its sole purpose is to be extended.

A class cannot be both abstract and final, since a final class cannot be extended. If the class contains abstract methods, then it must be declared abstract. Otherwise, a compilation error will be generated.

An abstract class can contain both abstract methods as well as ordinary ones.

Example

abstract class Caravan (private double price; private String model; private String year; public abstract void goFast (); // abstract method public abstract void changeColor ();)

Abstract method

An abstract method is a method declared with any implementation. The body of the method (implementation) is provided by the subclass. Abstract methods can never be final or strict.

Any class that extends an abstract class must implement all the abstract methods of the superclass, unless the subclass is an abstract class.

If a class in Java contains one or more abstract methods, then the class must be declared abstract. An abstract class does not have to contain abstract methods.

An abstract method ends with a semicolon. Example: public abstract sample ();

Example

public abstract class SuperClass (abstract void m (); // abstract method) class SubClass extends SuperClass (// implements abstract method void m () (.........))

Synchronized modifier

Synchronized modifier

The synchronized keyword is used to indicate that a method can only be accessed by one thread at a time. In Java, the synchronized modifier can be applied with any of the four access level modifiers.

Example

public synchronized void showDetails () (.......)

Transient modifier

An instance variable marked as transient instructs the Java virtual machine (JVM) to skip the specified variable when serializing the object that contains it.

This modifier is included in the statement, which creates a variable of the preceding class or data type of the variable.

Example

public transient int limit = 55; // will not persist public int b; // will persist

Volatile modifier

Volatile modifier- used in Java for streams.

In Java, the volatile modifier is used to let the JVM know that the variable access thread should always concatenate its own copy of the variable with the master copy in memory.

Accessing a volatile variable synchronizes all cached copied variables in memory. Volatile can only be applied to instance variables that are of type object or private. A volatile object reference can be null.

Example

public class MyRunnable implements Runnable (private volatile boolean active; public void run () (active = true; while (active) (// line 1 // some code here)) public void stop () (active = false; / / line 2))

Typically, run () is called on one thread (first time using Runnable in Java), and stop () is called from another thread. If line 1 uses a cached active value, then the loop cannot stop until you set active false on line 2.

In the next lesson, we will discuss the basic operators used in the Java language. This section will give you an overview of how you can use them during application development.

It is possible to control which parts of the program can access the members of the class. Access control helps prevent abuse. It is not always desirable to have access to a single variable or class method that should only work within the class itself.

Access method is determined access modifier, which is added when declaring. There are four of them:

  • private
  • public (open)
  • protected
  • default access when no modifier is present

Examples of modifier declarations (it must always come first):

Public int i; private double j, k; private int createMethod (int a) (...); public class Cat ()

As you can see, the modifier is applicable to a variable, method, class.

public

When using the keyword public you inform that the following class member declaration is available to everyone from any other code in your project.

Suppose the class is declared as public, and it has two methods. One private, second - public... You will have access to the classroom and to the second method, but not to the first, even though the class itself is open.

private

Keyword private means that access to a member of a class is not given to anyone other than the methods of that class. Other classes in the same package cannot access private members either.

All class helper methods should be declared as private to prevent them from being accidentally called in the package. The same applies to private fields within a class.

protected

Keyword protected is related to the concept of inheritance, in which new members are added to an already existing (base) class, while the original implementation remains unchanged. You can also change the behavior of existing class members. To create a new class based on an existing one, use the keyword extends.

If creating a new package uses inheritance from a class in another package, the new class only gains access to the public members from the original package. Sometimes the creator of a base class needs to give access to a particular method to derived classes, but close it from everyone else. In these cases, the keyword is used protected... The specifier protected also provides access within the package, i.e. members with this specifier are available to other classes in the same package.

By default, if no modifier is present, a class member is considered public within its own package, but not available to code outside of that package. If all the classes in your project are in the same package, then in essence the variable without the modifier is public ( public).

Consider a fictional class SillySensor

Public class SillySensor (private int sensorData; public SillySensor () (sensorData = 0;) private void calibrate (int iSeed) (// code for calibration) protected void seedCalibration (int iSeed) (calibrate (iSeed);) public int getSensorData ( ) (// Check sensor here return sensorData;))

The class is declared as public and is available in other classes. The class has a variable sensorData, which is available only in its class (private). The constructor is available in other classes ( public). Method calibrate () only works inside the class ( private). Method seedCalibration () available in its class or subclass ( protected). Method getSensorData () available in other classes ( public).

Modifier class
The Modifier class encodes all modifiers,
used in type declarations, in the form
constants:
ABSTRACT, FINAL, INTERFACE, NATIVE,
PRIVATE, PROTECTED, PUBLIC, STATIC,
STRICT, SYBCHRONIZED, TRANSIDENT,
VOLATILE.
Each of the constants has a request method of the form
isMod (int modifier) ​​(here Mod is one of the above
given names, for example, isPublic),
which returns true if the modifier
mod is present in the type declaration.

Let's look at an example. Let there be
field declaration
public static final int s = 10;
then the value returned by the method
getModifiers of the corresponding object
the Field class will look like
Modifier.PUBLIC | Modifier.STATIC |
Modifier.FINAL
The strictfp modifier is introduced
constant STRICT.
Methods - queries can be used in
following form

Modifier.isPrivate (field.getModifiers ());
this is equivalent to the following condition
(field.getModifiers () & Modifier.PRIVATE)! = 0
Field class
As part of the Field class, methods are implemented,
allowing to request information about
field type, as well as read and set it
meaning.
Let's consider some methods of the Field class
1.getType () - returns a class object
Class corresponding to the type of the current field.
For example, for a field of type int, we get
int.class.

2. Methods set and get - allow you to read
the current value of the field, and also set a new one.
Let's consider an example:
public static void printField (Object o,
String name) throws
NoSuchFieldException,
IllegalAccessException (
Field field = o.getClass (). GetField (name);
Short value = (Short) field.get (o);
System.out.println (value);
}
Those. the get method returns the value by which
refers to the corresponding field or object
class - shell.
An example of using the set method looks like this:

public static void setField (Object o, String name,
short nv) throws
NoSuchFieldException,
IllegalAccessException (
Field field = o.getClass (). GetField (name);
field.set (o, new Short (nv));
}
To store nv in a field of a given object
you need to use wrapper classes.
There are also methods that have the form
getPrimitiveType (like getInt) and
setPrimitiveType. These methods can
use to change fields in a class,
having a primitive type. For example,
field.setShort (o, nv);

Method class
Tools of the Method class - allow you to get
complete information regarding
method declarations of a specific class,
and call these methods in
the context of the given objects.
Consider the methods of the Method class.
1.public Class getReturnType () - returns
the Class object corresponding to the type
the value returned by the current method.
If instead of the return type in
the method declaration specifies a service
the word is void, the method in question will return
void.class object.

2.public Class getParameterTypes () - returns

parameters that are specified in the declaration
the current method. Objects are entered into an array at
in the order in which the parameters are listed in
method declaration. If the method does not have
parameters, an empty array is returned.
3.public Class getExceptionTypes () - returns
an array of Class objects corresponding to the types
exceptions that are specified in the sentence
throws declaration of the current method. Objects
are entered into the array in the order in which
the names of the types of exceptions are listed in
method declaration.

4.public Object invoke (Object onThis, Object args)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
Calls the method identified by the current object
Method, in the context of an onThis object with an assignment
the values ​​of the arguments passed by the args array.
For non-static methods, the choice of implementation
carried out on the basis of the actual type
the object identified by the onThis parameter. For
static methods onThis is not accepted in
attention and may be null.
The length of the args array must be the same as a number
parameters in the method declaration, and the object types of the array elements must be assignable
the corresponding types of method parameters - in
otherwise an exception will be thrown
IIlegalArgumentException.

10.

If the composition of the object determined
onThis, no type, member
which is the current method,
an exception is thrown
IllegalArgumentException.
If onThis is null and the method is not
static, an exception of type is thrown
NullPointerException.
If the execution of the called method
terminates abnormally, is thrown away
an exception of type InvocationTargetException.

11.

Let's look at an example. Let's call by means
reflection method return str.indexOf (".", 8)
then we have
try (
Сlass strClass = str.getClass ();
Method indexM = strClass.getMethod ("indexOf",
new Class (string.class, int.class));
Object result = indexM.invoke (str, new object (
".", new lnteger (8)));
return ((Integer) result) .intValue ();
}
catch (NoSuchMethodException e) (…… ..)
catch (invocationTargetException e) (…… ..)
catch (illegalAccessException e) (……)

12.

Constructor class
To create new instances (objects)
type method can be used
newlnstance of the Class object,
corresponding to this type.
The method calls the constructor with no arguments,
belonging to the type, and returns a reference
to a newly created object of class Object,
which must be explicitly converted to
required type.
Let's look at an example.

13.

static double testData = (0.3,1.3e-2, 7.9, 3.17);

try (
for (int arg = 0; arg< args.length; arg++){
String name = args;
Class classFor = Class.forName (name);
SortDouble sorter =
(SortDouble) classFor.newInstance ();
SortMetrics metrics = sorter.sort (testData);
System.out.println (name + ":" + metrics);
for (int i = 0; i< testData.length; i++)
System.out.println (“" + testData [i]);))
catch (Exception e) (System.err.println (e);))

14.

Newlnstance method when incorrect
application is capable of throwing out large
number of exception objects of various
types.
InstantiationException - if class, object
which should be created does not possess
a constructor with no arguments, or
defined as abstract, or in
really is an interface,
or performing the creation procedure
the object is interrupted for any other
reasons.
IllegalAccessException - if the class is either its
no argument constructor is available.

15.

SecurityException - if valid policy
security prohibits the creation of new objects
ExceptionInInitializerError - Thrown when
initializing the class.
Other methods are defined in the Constructor class.
public Сlass getParameterTypes ()

corresponding to the types of parameters that
specified in the current constructor declaration.
public Class getExceptionTypes ()
Returns an array of Class objects,
corresponding to the types of exceptions that
set in the throws clause of the declaration
the current constructor.

16.

public Object newlnstance (Object args)
throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
Uses the constructor provided by the current
a Constructor object to create and initialize
a new instance of the class in which the constructor
declared, passing the given arguments.
Returns a link to the newly created and
an initialized object. Args length
must match the number of parameters in
a constructor declaration, and the object types of the array elements must be assignable
the corresponding types of constructor parameters -
otherwise an exception will be thrown
IllegalArgumentException.

17.

Let's consider an example:
class Myclass (
private int a;
public Myclass (int k) (a = k;)
public int func (int a, int b) (return a + b;)
}
public class Main (
public static void main (String args) (
try (
String name = "Myclass";
Class mycl = Class.forName (name);
Class d = (int.class);
Constructor c = mycl.getConstructor (d);
Myclass ob = (Myclass) c.newInstance (new Object (
new Integer (10)));
System.out.println (ob.func (3,5)); )
catch (Exception e) ();
}}

18.

AccessibleObject class
The Field, Constructor and Method classes are
derived from the AccessibleObject class,
which makes it possible to resolve or
prohibit checking level access signs
languages ​​such as public and private.
The AccessibleObject class has methods
1.public void setAccessible (boolean flag)
Sets the object access flag to
according to the value of the argument: true
means the object no longer obeys
access rules set at the level
language (and will always be available), a false
forces the object to maintain the given
access level.
If the authority to change the access flag
not enough, an exception of type is thrown
SecurityException

19.

2.public static
void setAccessible (AccessibleObject array,
boolean flag)
Allows you to set the access flag to
objects passed as an array.
If during the processing of the next
object throws an exception of type
SecurityException Objects Located
in the array earlier, store the newly set
access level values, and all others
objects remain in the same state.
3.public boolean isAccessible ()
Returns the current value of the access flag
to the object

20.

Array class
Array class is used to create an array
by means of reflection.
There are two forms of the method used to create arrays
newInstance.
public Object newlnstance (Class compType, int length)
Returns a reference to a new array of type compType
given length length.
public Object newInstance (Class compType, int dim)
Returns a reference to a new multidimensional array of type
compType whose dimensions are given by values
elements of the parameter array dim.
If dim is empty or longer than
allowed number of dimensions (usually 255),

llegalArgumentException.

21.

Let's look at some examples.
Example 1. Let's form an array of type byte
byte ba = (byte)
Array.newlnstance (byte.class, 13);
This is the same as
byte ba = new byte;
Example 2.
int dims = (4, 4);
double matrix = (double)
Array.newlnstance (double.class, dims);
This is the same as
double matrix = new double;

22.

The Array class has get and set methods.
Let an array xa of values ​​of type int be given; then
expression xa [i] will match:
Integer n = Array.get (xa, i)
You can assign a value to an array element like this:
xa [i] = 23; is the same as
Array.set (xa, i, new Integer (23));
Package class
Calling the getPackage method of the Class class allows
get an object of class Package containing
description of the package that contains the
class (the Package class itself is located in the package
java.lang).
The getName () method of the Package object returns
the full name of the current package.

23.

Proxy class
The Proxy class allows you to dynamically create
classes that implement one or more
interfaces.
Suppose there is a class A,
implementing some interfaces.
Java machine at runtime can
generate proxy class for given
class A, i.e. a class that
implements all interfaces of class A, but
replaces calling all methods of these
interfaces to call the invoke method,
the InvocationHandler interface, for
which you can define your
implementation.

24.

Creates a proxy class using a method call
Proxy.getProxyClass which accepts a ClassLoader and
an array of interfaces, and returns an object
class java.lang.Class which is loaded with
of the passed in ClassLoader and implements the passed in array
interfaces.
There are a number of restrictions on the transmitted parameters:
1. All objects in the interfaces array must be
interfaces. They cannot be classes or
primitives.
2. The interfaces array cannot contain two identical
objects.
3. All interfaces in the interfaces array must be
loaded by the ClassLoader that is passed to the method
getProxyClass.
4. All non-public interfaces must be defined
in the same package, otherwise the generated proxy class
will not be able to implement them all.

25.

5. No two interfaces can contain
method with the same name and
parameter signature, but with different
return types.
6. The length of the interfaces array is limited
65535 interfaces. No Java class
cannot implement more than 65535
interfaces.

26.

Dynamic proxy class properties
1. The proxy class is public, provided
is final and is not abstract.
2. The default proxy class name is not
defined, but starts at Proxy. Everything
namespace starting with Proxy
reserved for proxy classes
(This is not required in recent versions of Java.)
3. Proxy class inherits from
java.lang.reflect.Proxy.
4. The proxy class implements all interfaces,
transferred at creation, in the order of transfer.

27.

5. If the proxy class implements a non-public
interface, then it will be generated in the package
which defines this very non-public
interface. In general, a package in which
the proxy class will be generated undefined.
6. The Proxy.isProxyClass method returns true for
classes created with
Proxy.getProxyClass and for object classes,
created with Proxy.newProxyInstance and
false otherwise.
This method is used by the subsystem
Java security and you need to understand that for
a class just inherited from
java.lang.reflect.Proxy it will return false.

28.

The properties of the created instance of the proxy class are as follows:
1. The object of the proxy class is cast to all interfaces,
passed in the interfaces array. If IDemo is one of
of the passed interfaces, then the proxy instanceof operation
IDemo will always return true and the (IDemo) proxy operation
will complete correctly.
2. Static method Proxy.getInvocationHandler
returns the call handler passed on creation
an instance of the proxy class. If transferred to the given
method object is not an instance of a proxy class, then
an IllegalArgumentException exception will be thrown.
3. The call handler class implements the interface
InvocationHandler in which the invoke method is defined,
having the following signature:
public Object invoke (Object proxy, Method method,
Object args) throws Throwable

29.

Let's consider an example:
package javaapplication3;
interface Account (
double getBalance ();
void changeBalance (int sum);
void percents (double per);)
class MyAccount implements Account (
private double balance;
public MyAccount () (balance = 0.0;)
public double getBalance () (return balance;)
public void changeBalance (int sum) (
balance + = sum;)
public void percents (double per) (
balance + = balance * per / 100; ); )

30.

class MyAccountProxy implements
InvocationHandler (
private Account ac;
public MyAccountProxy (Account acc) (ac = acc;)
public static Account newInstance (Account da) (
return (Account) Proxy.newProxyInstance (
da.getClass (). getClassLoader (),
da.getClass (). getInterfaces (),
new MyAccountProxy (da));
}

31.

public Object invoke (Object proxy,
Method method, Object args)
throws Throwable (
if (method.getName () == "percents") (
double d = ((Double) args) .doubleValue ();
if (d<0) d=0;
if (d> 30) d = 30;
args = new Double (d);

else (
return method.invoke (ac, args); )
}
}

32.

public class Main (
public static void main (String args) (
MyAccount ma = new MyAccount ();
Account
a = (Account) MyAccountProxy.newInstance (ma);
a.changeBalance (150);

a.percents (20);
System.out.println (a.getBalance ());
a.percents (35);
System.out.println (a.getBalance ());))

33.

Loading classes
The runtime system loads classes as
the emergence of the need for them.
Functional features of boot procedures
classes essentially depend on
implementations of Java virtual machines, but in
in most cases to find classes,
addressed by the application but not loaded
by the executing system, the mechanism is applied
view the class search path.
To create an application that is able to
load classes in ways other than
provided by default, you should
use an object of the class ClassLoader,
able to get the bytecode for the implementation of the desired
class and load it into the runtime environment
systems.

34.

The ClassLoader class is an abstract class.
To create your own classloader,
it is necessary to create a class that inherits from
ClassLoader and override method
protected Class findClass (String name) throws
ClassNotFoundException
Which finds the bytecode of the class with the given
named name and loads the data into the environment
the virtual machine by returning a Class object,
representing the found class.
The loader object is able to delegate
authority to load classes to "parent"
the parent class loader.
The "parent" classloader can be
given as an argument to the class constructor
ClassLoader.

35.

protected ClassLoader ()
Creates a ClassLoader object, implicitly
using as "parent"
classloader system loader
(which can be obtained by
call the getSystemClassLoader method).
protected ClassLoader (ClassLoader parent)
Creates a ClassLoader object using
the specified "parent" classloader.
The main part of the ClassLoader class
is the loadClass method

36.

public Сlass loadClass (String name) throws
ClassNotFoundException
returns the Class object for the class with the given
name and optionally loads this
Class. If the class cannot be loaded,
an exception of type is thrown
ClassNotFoundException.
The class loading scheme offered by the method
loadClass is the default and usually not
overridden looks like this:
1.check by calling a method
findLoadedClass of class ClassLoader, not
whether the specified class has been loaded before; as part of
ClassLoader provides a table of objects
Class for all classes loaded by means
the current class loader; if the class was
loaded before, findLoadedClass method
will return a reference to an existing Class object;

37.

2.if the class was not loaded, it is called
loadClass of the "parent" loader
classes; if the current bootloader is not
possesses a "parent", is used
system class loader;
3.if the class is still not loaded,
the findClass method is called doing
searching and loading a class.
Thus, it is necessary to implement
native versions of the following methods
ClassLoader:

38.

protected synchronized Class
loadClass (String name, boolean resolve)

protected Class findClass (String name)
throws ClassNotFoundException
protected java.net.URL findResource (String name)
protected java.util.Enumeration
findResources (String name) throws IOException
(The abstract class ClassLoader represents
only the implementation of the loadClass method based on
on protected methods - findLoadedClass and findClass).

39.

Let's look at an example.
class PlayerLoader extends ClassLoader (
public Class findClass (String name) throws
ClassNotFoundException (
try (
byte buf = bytesForClass (name);
return defineClass (name, buf, 0, buf.length);
}
catch (IOException e) (
throw new ClassNotFoundException (e.toString ());
}
}
// ... Method declarations bytesForClass and others
methods
}

40.

The findClass method usually does two
functions.
First, it must detect the bytecode
of the given class and store it in an array
byte type - this duty in the example
assigned to the bytesForСlass method.
Second, it uses the applied method
defineСlass to execute the actual
loading the class defined by the bytecode.
The defineСlass method has the form

41.

protected final Class defineClass (String name,
byte data, int offset, int length) throws
ClassFormatError
Returns the Class object for the class with the given name
name; the binary representation of the class is passed to
as an array data.
Only bytes are used to load the class,
contained in the elements of the data array with indices
offset to offset + length. If bytes from the specified
gap do not match the required format
class description, the exception object is thrown
of type ClassFormatError.
The method is responsible for maintaining the reference to the object
Class for loaded class in loaded table
classes viewed by the findLoadedClass method.

42.

Consider the bytesForClass method.
protected byte bytesForClass (String name) throws
lOException, ClassNotFoundException (
FileInputStream in = null;
try (


if (length == 0) throw new ClassNotFoundException (name);
byte buf = new byte;

return buf;
}
finally (
if (in! = null) in.close ();
}
}

43.

Thus, the complete code looks like:
import java.lang.reflect. *;
import java.io. *;
class MyClassLoader extends ClassLoader (
public ClassfindClass (String name) throws
ClassNotFoundException (
byte buf = ReadFromBuffer (name);
if (name.equals ("MyInterface1")) (

) else if (buf == null) (
return findSystemClass (name);
) else (
return defineClass (name, buf, 0, buf.length);
}
}

44.

protected byte ReadFromBuffer (String name) throws
ClassNotFoundException (
FileInputStream in = null;
try (
in = new FileInputStream (name + ".class");
int length = in.available (); // number of bytes available
if (length == 0) throw
new ClassNotFoundException (name);
byte buf = new byte;
in.read (buf); // Read bytes
return buf;
}
catch (FileNotFoundException e) (return null;)
catch (IOException e) (return null;)
finally (
try (if (in! = null) in.close ();)
catch (IOException e) ()
}
}

45.

protected synchronized Class
loadClass (String name, boolean resolve) throws
ClassNotFoundException (
Class result = findClass (name);
if (resolve) resolveClass (result);
return result;
}
}

46.

public class Main1 (
public static void main (String args) (
try (
String name = "Myclass";
ClassLoader ld = new MyClassLoader ();
Class cl = Class.forName (name, true, ld);
Constructor s = cl.getConstructor (int.class);
MyInterface1
ob = (MyInterface1) s.newInstance (
new Integer (8));
System.out.println (ob.func (3,5));
) catch (Exception e) ();
}
}

47.

public interface MyInterface1 (
public int func (int a, int b);
}
public class Myclass implements MyInterface1 (
private int a;
public Myclass (int k) (a = k;)
public int func (int a, int b) (return a + b;)