SlideShare a Scribd company logo
Java course - IAG0040




                 Networking,
             Reflection & Logging



Anton Keks                             2011
Networking
 ●   Java provides cross-platform networking facilities
 ●
     java.net and javax.net packages contain many useful classes
 ●   API is generally protocol independent, but implementation supports
     mostly Internet transport protocols, e.g. TCP and UDP
 ●   java.net.InetAddress represents an IP address (immutable)
      –   Inet4Address represents 32-bit IPv4 addresses (4 billions)
      –   Inet6Address represents 128-bit IPv6 addresses (3.4 x 10 38)
      –   It is able to detect address types, provides naming services, and
          various other checks and conversions
      –   Create using InetAddress.getByAddress(...), getByName(...)
          or getLocalHost()
      –   Many getXXX() and isXXX() methods provided
Java course – IAG0040                                                     Lecture 9
Anton Keks                                                                  Slide 2
Sockets
 ●   Sockets are used as endpoints in network communication
 ●
     java.net.InetSocketAddress represents an address-port pair
 ●   There are several types of sockets in Java
      –   Socket and ServerSocket – connection-oriented streaming reliable client
          and server sockets (TCP)
      –   SSLSocket and SSLServerSocket – client and server sockets for secure
          encrypted communication (TCP via SSL)
      –   DatagramSocket – packet-oriented unreliable socket for both sending and
          receiving data (UDP), can be used for both unicasting and broadcasting
      –   MulticastSocket – datagram socket with multicasting support
 ●   Socket implementations depend on respective factory classes. Direct
     usage uses the default socket factory for the given socket type.

Java course – IAG0040                                                   Lecture 9
Anton Keks                                                                Slide 3
Networking Exceptions
 ●
     Most networking exceptions extend
     SocketException
 ●   SocketException extends IOException, showing
     that networking is highly related to all other
     more generic I/O classes




Java course – IAG0040                         Lecture 9
Anton Keks                                      Slide 4
Streaming Sockets
 ●   Socket and ServerSocket can be used for streaming
 ●   Underlying Socket implementations are provided by
     SocketImplFactory classes by the means of SocketImpl classes.
     Default implementation is plain TCP.
 ●   getInputStream() and getOutputStream() are used for
     obtaining the streams, both can be used simultaneously
 ●   Various socket options may be set using provided set methods
 ●   There are many informative is/get methods provided
 ●   Stream sockets must be closed using the close() method
      –   it closes both streams automatically as well


Java course – IAG0040                                      Lecture 9
Anton Keks                                                   Slide 5
Datagram Sockets
 ●
     DatagramSocket is used for sending and receiving of
     DatagramPackets; receiving is actually 'listening'
 ●
     Connection-less, no streams provided
 ●   connect() and disconnect() is used for
     selecting/resetting the remote party's address and port
 ●
     Special addresses can be used for sending/receiving of
     broadcast packets, e.g. 192.168.0.255
 ●
     MulticastSocket can be used for joining/leaving multicast
     groups of DatagramSockets. Multicast groups have special
     addresses.

Java course – IAG0040                                     Lecture 9
Anton Keks                                                  Slide 6
URL and URLConnection
●
    Java also provides higher-level networking APIs than Sockets
●
    URI and URL classes provide construction and parsing of the
    respective Strings (all URLs are URIs, however)
     –   URI is a newer class and provides encoding/decoding of
         escaped symbols, like %20
     –   Conversions back and forth are possible using toURI()
         and toURL() methods
●
    URLConnection provides API for reading/writing of the
    resources referenced by URLs
●   url.openConnection() returns a subclass of
    URLConnection, according to the registered protocol-specific
    URLStreamHandler
                                                             Lecture 9
                                                               Slide 7
URL and URLConnection (cont)
●   Obtained URLConnection can be used for setting various
    parameters (headers)
    –   Actual connection is opened using the connect() method
    –   Both getInputStream() and getOutputStream() are
        provided
    –   getContent() returns an Object according to the MIME
        type of the resource, which ContentHandler is provided by
        the ContentHandlerFactory
●   url.openStream() is a shortcut if you need to just retrieve
    the data without any extra features
●
    Proxy/ProxySelector can be used for proxying of traffic
                                                         Lecture 9
                                                           Slide 8
Networking Task
●
    Implement the FileDownloader (eg using existing
    DataCopier implementation)
●
    Try your code with various Input and Output streams
        –   Files, Sockets, URLs
●
    Create FileSender and FileReceiveServer classes. Reuse
    already written code to send file content over the socket
    and save content to another file on the server end




                                                       Lecture 9
                                                         Slide 9
Reflection API
 ●   The reflection API represents, or reflects, the
     classes, interfaces, and objects in the current
     JVM
     –   It is possible to dynamically collect information about
         all aspects of compiled entities, even access private
         fields
 ●   Reflection API is in java.lang and
     java.lang.reflect packages
 ●   Note: Reflection API is also full of generics
     (for convenience)

Java course – IAG0040                                      Lecture 9
Anton Keks                                                  Slide 10
Reflection API usage
 ●
     Where is it appropriate to use it?
     –   various plugins and extensions: load classes by
         name, etc
     –   JUnit uses reflection for finding test methods
         either by name or annotations
     –   Many other famous frameworks use reflection, e.g.
         Hibernate, Spring, Struts, Log4J, JUnit, etc
 ●
     Caution: use reflection only when it is absolutely
     necessary!

Java course – IAG0040                                     Lecture 9
Anton Keks                                                 Slide 11
Examining Classes
●
    Class objects reflect Java classes
     –   Every Object provides the getClass() method
     –   Various methods of Class return instances of Field, Method, Constructor,
         Package, etc
          ●   methods in plural return arrays, e.g. getFields(), getMethods()
          ●   methods in singular return single instances according to search
              criteria, e.g. getField(...), getMethod(...)
     –   Class can also represent primitive types, interfaces, arrays, enums and
         annotations
●   Java supports Class literals, e.g. String.class, int.class
●   Class.forName() is used for loading classes dynamically
●   Modifiers: Modifier.isPublic(clazz.getModifiers())
●   getSuperclass() returns the super class
Java course – IAG0040                                                      Lecture 9
Anton Keks                                                                  Slide 12
Instantiating Classes
 ●   clazz.newInstance() works for default constructors
 ●   Otherwise getConstructor(...) will provide a Constructor
     instance, which has its own newInstance(...)
 ●   Singular Constructor and Method finding methods take Class
     instances for matching of parameters:
     –   Constructor c = clazz.getConstructor(int.class,
         Date.class);
 ●   Then, creation (newInstance) or invocation (invoke) takes
     the real parameter values:
     –   Object o = c.newInstance(3, new Date());
     –   Primitive values are autoboxed to their wrapper classes

Java course – IAG0040                                              Lecture 9
Anton Keks                                                          Slide 13
Reflection Tips
 ●   Array class provides additional options for dynamic manipulation of arrays
 ●   Even this works: byte[].class
 ●   Retrieve class name of any object: object.getClass().getName()
 ●   Don't hardcode class names in Strings:
     MegaClass.class.getName() or .getSimpleName() is better
 ●   Accessing private fields:
      –   boolean wasAccessible = field.getAccessible();
          field.setAccessible(true);
          Object value = field.get(instance);
          field.setAccessible(wasAccessible);
 ●   Dynamic proxies allow to wrap objects and intercept method calls on them
     defined in their implemented interfaces:
      –   Object wrapped = Proxy.newProxyInstance(
              o.getClass().getClassLoader(), o.getClass().getInterfaces(),
              new InvocationHandler() { ... });
Java course – IAG0040                                                  Lecture 9
Anton Keks                                                              Slide 14

More Related Content

PDF
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
PPTX
Java se7 features
PPTX
Manuel - SPR - Intro to Java Language_2016
PPTX
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
PDF
Java Day-3
PPT
Core java
PPTX
OOPs with Java - Packaging and Access Modifiers
PPTX
Omnet++
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Java se7 features
Manuel - SPR - Intro to Java Language_2016
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
Java Day-3
Core java
OOPs with Java - Packaging and Access Modifiers
Omnet++

What's hot (19)

DOC
Serialization in .NET
PPTX
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
PPTX
2 second lesson- attributes
PPTX
Core java1
PPTX
Session 10 - OOP with Java - Abstract Classes and Interfaces
PDF
28 networking
PPT
Core Java Programming | Data Type | operator | java Control Flow| Class 2
PPTX
Just entity framework
PPSX
Arrays in Java
PDF
Getting Started With Scala
PPTX
Java - Sockets
PDF
Basics of building a blackfin application
PDF
Java Day-7
PDF
Scala eXchange opening
PDF
Scala: Object-Oriented Meets Functional, by Iulian Dragos
PDF
04 sorting
PPTX
04 Java Language And OOP Part IV
PPT
PDF
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Serialization in .NET
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
2 second lesson- attributes
Core java1
Session 10 - OOP with Java - Abstract Classes and Interfaces
28 networking
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Just entity framework
Arrays in Java
Getting Started With Scala
Java - Sockets
Basics of building a blackfin application
Java Day-7
Scala eXchange opening
Scala: Object-Oriented Meets Functional, by Iulian Dragos
04 sorting
04 Java Language And OOP Part IV
Ikenna Okpala: London Java Community: Wicket and Scala - 27/07/2010.
Ad

Viewers also liked (20)

PDF
Java Course 4: Exceptions & Collections
PDF
Java Course 7: Text processing, Charsets & Encodings
PDF
Java Course 2: Basics
PDF
Choose a pattern for a problem
PDF
Java Course 12: XML & XSL, Web & Servlets
PDF
Java Course 15: Ant, Scripting, Spring, Hibernate
PDF
Scrum is not enough - being a successful agile engineer
PPT
java packages
PDF
Java Course 14: Beans, Applets, GUI
PDF
Java Course 6: Introduction to Agile
PDF
Java Course 3: OOP
PDF
Java Course 1: Introduction
PDF
Java Course 13: JDBC & Logging
PPTX
Java package
PPS
Packages and inbuilt classes of java
PDF
Java Course 5: Enums, Generics, Assertions
PDF
Simple Pure Java
PDF
Database Refactoring
PDF
Java Course 11: Design Patterns
PDF
Java Course 10: Threads and Concurrency
Java Course 4: Exceptions & Collections
Java Course 7: Text processing, Charsets & Encodings
Java Course 2: Basics
Choose a pattern for a problem
Java Course 12: XML & XSL, Web & Servlets
Java Course 15: Ant, Scripting, Spring, Hibernate
Scrum is not enough - being a successful agile engineer
java packages
Java Course 14: Beans, Applets, GUI
Java Course 6: Introduction to Agile
Java Course 3: OOP
Java Course 1: Introduction
Java Course 13: JDBC & Logging
Java package
Packages and inbuilt classes of java
Java Course 5: Enums, Generics, Assertions
Simple Pure Java
Database Refactoring
Java Course 11: Design Patterns
Java Course 10: Threads and Concurrency
Ad

Similar to Java Course 9: Networking and Reflection (20)

PDF
Lecture10
PDF
Java features. Java 8, 9, 10, 11
PDF
Core Java Programming Language (JSE) : Chapter XII - Threads
PDF
Writing Plugged-in Java EE Apps: Jason Lee
PPTX
NETWORKING EN JAVA CLASSES IN THE JDK...
PPT
Jacarashed-1746968053-300050282-Java.ppt
PPTX
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
PPTX
Java seminar.pptx
PDF
Java training materials for computer engineering.pdf
PDF
04 android
PDF
PDF
Java Enterprise Edition
PPT
Lec8_Java Advanced class features_Part 1V.ppt
PPTX
Unit3 packages & interfaces
PDF
Java lab-manual
PDF
Core Java Tutorial
PDF
Lecture 5 interface.pdf
PDF
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
PDF
Dynamic Proxy by Java
Lecture10
Java features. Java 8, 9, 10, 11
Core Java Programming Language (JSE) : Chapter XII - Threads
Writing Plugged-in Java EE Apps: Jason Lee
NETWORKING EN JAVA CLASSES IN THE JDK...
Jacarashed-1746968053-300050282-Java.ppt
3160707_AJava_GTU_Study_Material_Presentations_Unit-1_16032021121225PM.pptx
Java seminar.pptx
Java training materials for computer engineering.pdf
04 android
Java Enterprise Edition
Lec8_Java Advanced class features_Part 1V.ppt
Unit3 packages & interfaces
Java lab-manual
Core Java Tutorial
Lecture 5 interface.pdf
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Dynamic Proxy by Java

Recently uploaded (20)

PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
Teaching material agriculture food technology
PPTX
Cloud computing and distributed systems.
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Electronic commerce courselecture one. Pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
sap open course for s4hana steps from ECC to s4
Programs and apps: productivity, graphics, security and other tools
Mobile App Security Testing_ A Comprehensive Guide.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Digital-Transformation-Roadmap-for-Companies.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
The AUB Centre for AI in Media Proposal.docx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Encapsulation_ Review paper, used for researhc scholars
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Teaching material agriculture food technology
Cloud computing and distributed systems.
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
“AI and Expert System Decision Support & Business Intelligence Systems”
Electronic commerce courselecture one. Pdf
MYSQL Presentation for SQL database connectivity
MIND Revenue Release Quarter 2 2025 Press Release
Network Security Unit 5.pdf for BCA BBA.
Understanding_Digital_Forensics_Presentation.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
sap open course for s4hana steps from ECC to s4

Java Course 9: Networking and Reflection

  • 1. Java course - IAG0040 Networking, Reflection & Logging Anton Keks 2011
  • 2. Networking ● Java provides cross-platform networking facilities ● java.net and javax.net packages contain many useful classes ● API is generally protocol independent, but implementation supports mostly Internet transport protocols, e.g. TCP and UDP ● java.net.InetAddress represents an IP address (immutable) – Inet4Address represents 32-bit IPv4 addresses (4 billions) – Inet6Address represents 128-bit IPv6 addresses (3.4 x 10 38) – It is able to detect address types, provides naming services, and various other checks and conversions – Create using InetAddress.getByAddress(...), getByName(...) or getLocalHost() – Many getXXX() and isXXX() methods provided Java course – IAG0040 Lecture 9 Anton Keks Slide 2
  • 3. Sockets ● Sockets are used as endpoints in network communication ● java.net.InetSocketAddress represents an address-port pair ● There are several types of sockets in Java – Socket and ServerSocket – connection-oriented streaming reliable client and server sockets (TCP) – SSLSocket and SSLServerSocket – client and server sockets for secure encrypted communication (TCP via SSL) – DatagramSocket – packet-oriented unreliable socket for both sending and receiving data (UDP), can be used for both unicasting and broadcasting – MulticastSocket – datagram socket with multicasting support ● Socket implementations depend on respective factory classes. Direct usage uses the default socket factory for the given socket type. Java course – IAG0040 Lecture 9 Anton Keks Slide 3
  • 4. Networking Exceptions ● Most networking exceptions extend SocketException ● SocketException extends IOException, showing that networking is highly related to all other more generic I/O classes Java course – IAG0040 Lecture 9 Anton Keks Slide 4
  • 5. Streaming Sockets ● Socket and ServerSocket can be used for streaming ● Underlying Socket implementations are provided by SocketImplFactory classes by the means of SocketImpl classes. Default implementation is plain TCP. ● getInputStream() and getOutputStream() are used for obtaining the streams, both can be used simultaneously ● Various socket options may be set using provided set methods ● There are many informative is/get methods provided ● Stream sockets must be closed using the close() method – it closes both streams automatically as well Java course – IAG0040 Lecture 9 Anton Keks Slide 5
  • 6. Datagram Sockets ● DatagramSocket is used for sending and receiving of DatagramPackets; receiving is actually 'listening' ● Connection-less, no streams provided ● connect() and disconnect() is used for selecting/resetting the remote party's address and port ● Special addresses can be used for sending/receiving of broadcast packets, e.g. 192.168.0.255 ● MulticastSocket can be used for joining/leaving multicast groups of DatagramSockets. Multicast groups have special addresses. Java course – IAG0040 Lecture 9 Anton Keks Slide 6
  • 7. URL and URLConnection ● Java also provides higher-level networking APIs than Sockets ● URI and URL classes provide construction and parsing of the respective Strings (all URLs are URIs, however) – URI is a newer class and provides encoding/decoding of escaped symbols, like %20 – Conversions back and forth are possible using toURI() and toURL() methods ● URLConnection provides API for reading/writing of the resources referenced by URLs ● url.openConnection() returns a subclass of URLConnection, according to the registered protocol-specific URLStreamHandler Lecture 9 Slide 7
  • 8. URL and URLConnection (cont) ● Obtained URLConnection can be used for setting various parameters (headers) – Actual connection is opened using the connect() method – Both getInputStream() and getOutputStream() are provided – getContent() returns an Object according to the MIME type of the resource, which ContentHandler is provided by the ContentHandlerFactory ● url.openStream() is a shortcut if you need to just retrieve the data without any extra features ● Proxy/ProxySelector can be used for proxying of traffic Lecture 9 Slide 8
  • 9. Networking Task ● Implement the FileDownloader (eg using existing DataCopier implementation) ● Try your code with various Input and Output streams – Files, Sockets, URLs ● Create FileSender and FileReceiveServer classes. Reuse already written code to send file content over the socket and save content to another file on the server end Lecture 9 Slide 9
  • 10. Reflection API ● The reflection API represents, or reflects, the classes, interfaces, and objects in the current JVM – It is possible to dynamically collect information about all aspects of compiled entities, even access private fields ● Reflection API is in java.lang and java.lang.reflect packages ● Note: Reflection API is also full of generics (for convenience) Java course – IAG0040 Lecture 9 Anton Keks Slide 10
  • 11. Reflection API usage ● Where is it appropriate to use it? – various plugins and extensions: load classes by name, etc – JUnit uses reflection for finding test methods either by name or annotations – Many other famous frameworks use reflection, e.g. Hibernate, Spring, Struts, Log4J, JUnit, etc ● Caution: use reflection only when it is absolutely necessary! Java course – IAG0040 Lecture 9 Anton Keks Slide 11
  • 12. Examining Classes ● Class objects reflect Java classes – Every Object provides the getClass() method – Various methods of Class return instances of Field, Method, Constructor, Package, etc ● methods in plural return arrays, e.g. getFields(), getMethods() ● methods in singular return single instances according to search criteria, e.g. getField(...), getMethod(...) – Class can also represent primitive types, interfaces, arrays, enums and annotations ● Java supports Class literals, e.g. String.class, int.class ● Class.forName() is used for loading classes dynamically ● Modifiers: Modifier.isPublic(clazz.getModifiers()) ● getSuperclass() returns the super class Java course – IAG0040 Lecture 9 Anton Keks Slide 12
  • 13. Instantiating Classes ● clazz.newInstance() works for default constructors ● Otherwise getConstructor(...) will provide a Constructor instance, which has its own newInstance(...) ● Singular Constructor and Method finding methods take Class instances for matching of parameters: – Constructor c = clazz.getConstructor(int.class, Date.class); ● Then, creation (newInstance) or invocation (invoke) takes the real parameter values: – Object o = c.newInstance(3, new Date()); – Primitive values are autoboxed to their wrapper classes Java course – IAG0040 Lecture 9 Anton Keks Slide 13
  • 14. Reflection Tips ● Array class provides additional options for dynamic manipulation of arrays ● Even this works: byte[].class ● Retrieve class name of any object: object.getClass().getName() ● Don't hardcode class names in Strings: MegaClass.class.getName() or .getSimpleName() is better ● Accessing private fields: – boolean wasAccessible = field.getAccessible(); field.setAccessible(true); Object value = field.get(instance); field.setAccessible(wasAccessible); ● Dynamic proxies allow to wrap objects and intercept method calls on them defined in their implemented interfaces: – Object wrapped = Proxy.newProxyInstance( o.getClass().getClassLoader(), o.getClass().getInterfaces(), new InvocationHandler() { ... }); Java course – IAG0040 Lecture 9 Anton Keks Slide 14