- How to detect time of ClassLoading
- 2 Answers 2
- Load the Current Date and Time in Java
- Load Current Date/Time Using Java
- About The Load the Current Date and Time In Java
- Class Loading time in Java
- Rollerball
- People also ask
- 1 Answers
- How do I save and load the current time in java?
- 4 Answers 4
- tl;dr
- Serializing
- Formatted strings
- Track Date-Time Values, Not Milliseconds
- Joda-Time | java.time
- ISO 8601
How to detect time of ClassLoading
I have a TrirdParty API that contains a CLass [let’s say A]. It has a bizarre static block similar to the following:
class A < static < try < System.loadLibrary("libraryName"); >catch(UnsatisfiedLinkError ue) < System.exit(0); >> //other stuff >
I want to prevent the call to System.exit() with a overridden SecurityManager . However I want to override the SecurityManager just before this static block is executed and right after that I want to restore the original security manager. I know how to replace/override/restore SecurityManager . My problem is how do I determine when the static block will be called [basically when the class will be loaded] so that just before that I will use my own SecurityManager to prevent the System.exit() and after that restore the original SecurityManager . Please note that it is important to override the security manager only for the time duration when the static block is executed. EDIT: Changing the source is not an option for licensing reasons.
I can do that but I have to be sure that the class has not been loaded prior to my code. My aim is to prevent the System.exit().
If this code can be loaded before your code, then how can you do anything to prevent the System.exit()?
@jdigital. what I meant was that I must be sure that wherever I put my code it must come before that static block. I cannot put the code into production without the guarantee.
2 Answers 2
why can’t you just replace the static<> block with the one you need by using some bytecode crunching library, like Javassist?
Bytecode access doesn’t work at the source level. However, if this code loads before yours (re: discussion above), then it won’t help.
it is always possible to intercept the class loading process with -javaagent or bootstrap classloader.. Then you’re not editing the source code but transforming the code on the fly 🙂 sure thing, if the license doesn’t allow you to patch the binary classes in runtime then it is another story.
I think that you are basically stuffed.
Yes, it is (in theory at least) possible to block the call System.exit() via a security manager. But what happens then?
- Static initializer in class attempts to call System.exit() .
- SecurityManager says no you can’t and throws SecurityException
- Static initialization of the class fails with uncaught exception
- Initialization of the class you were originally trying to initialize (implicitly) fails.
You can in theory catch the exception. But that doesn’t get you very far, because the JVM will only attempt to perform static initialization once. If that fails, and you try again, the JVM will simply throw ClassNotFoundError (I think), repeating the original exception as the cause.
The only way to get the class initialization to happen again is to throw away the classloader that loaded the offending classes in the first place, create a new one, and start loading again. And then you are back to the original problem.
Bottom line: if you really can’t change the code, you are stuffed.
Even if you could make this work, it sounds like a poor solution / non-solution to your problem. The LinkageError exception means that the library has failed to load a native library, and that the corresponding native method calls into the library will fail with an Error . At best you’ll end up with a library where some bits work and others don’t.
You should focus on obtaining the right native library for your platform and/or configuring the JVM so that it can find it. Or finding a better alternative to the 3rd-party library that isn’t encumbered with intrusive license enforcement crap.
Load the Current Date and Time in Java
This tutorial is about how to Load Current Date/Time Using Java. This tutorial will help you on how to load the system current date and time through label element in Java. The program will display the current date and time base from the computer system.
Some of the computer systems are using the date and time to track and identify the program transactions. The program includes Point of Sale System, Inventory System, Billing System and much more.
Load Current Date/Time Using Java
1.Create/Add a new JFrame Form inside your source package.
2. Design your Form just like what I do in the image below.
3. Add the following import codes above your class to access the required libraries.
[java]import java.text.SimpleDateFormat;import java.util.Date;
import java.util.GregorianCalendar;[/java]
4. Create a new method inside your class.
[java]public final void loadDateTime()5. Insert the following codes inside your new created method.
[java]//load date/timeDate date = GregorianCalendar.getInstance().getTime();
Date time = GregorianCalendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat(“MMMM dd, yyyy”);
SimpleDateFormat sdf2 = new SimpleDateFormat(“HH:mm:ss”);
jLabel2.setText(sdf2.format(time));
jLabel1.setText(sdf.format(date));[/java]
6. Copy the method name and insert it into your public method inside your class.
[java]public LoadSystemDateTime() initComponents();loadDateTime();
>[/java]
7. Run your program and the output should look like the image below.
About The Load the Current Date and Time In Java
Remember that the computer system date and time will be displayed in the program you created whether it is updated or outdated. If you have comments and question about Load Current Date/Time Using Java. Feel free to use our contact information.
If you find this article useful, you can share this to your friends.
Class Loading time in Java
Hi stackoverflow members, Here is a little question related to the actual meaning of «class loading time».
For example the following code:
public class Sequence < Sequence() < System.out.print("c "); > < System.out.print("y "); >public static void main(String[] args) < System.out.println("Indeed"); new Sequence().go(); >void go() < System.out.print("g "); >static < System.out.println("x "); >>
It does print out first «x» which is static so the static init blocks are always loaded at «class loading time». I get it, but do you know exactly when this loading time happens? I thought when the class first gets called in the main method by creating the first object but in that case the result should have been different by printing out first «Indeed». Anyone can help me clarifying this doubt? I have checked other post talking about this argument in general but still I think would be much clearer (at least for me) getting to know when exactly, in the code reported above, the «class loading time» happens.
Rollerball
People also ask
Java ClassLoader is used to load the classes at run time. In other words, JVM performs the linking process at runtime. Classes are loaded into the JVM according to need. If a loaded class depends on another class, that class is loaded as well. When we request to load a class, it delegates the class to its parent.
Loading involves obtaining the byte array representing the Java class file. Verification of a Java class file is the process of checking that the class file is structurally well-formed and then inspecting the class file contents to ensure that the code does not attempt to perform operations that are not permitted.
2 Answers. Save this answer. Show activity on this post. A classloader can only actually load a class once!
Classloading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need for class initialization occurs. If Class is loaded before it’s actually being used it can sit inside before being initialized.
1 Answers
The answer to your question is in the JLS Chapter 12.4.1 When Initialization Occurs
- T is a class and an instance of T is created.
- T is a class and a static method declared by T is invoked.
- A static field declared by T is assigned.
- A static field declared by T is used and the field is not a constant variable (§4.12.4).
- T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
I recommend you start reading a few lines above at JLS Chapter 12.4. Initialization of Classes and Interfaces
Just start with Chapter 12. Execution, it exactly describes when a class needs to be loaded. The initialization will be done after loading it.
How do I save and load the current time in java?
I need to be able to save and load the current time in java. I could use System.currentTimeMillis() to store it in a long, but I also need to be able to write it out in different formats, like; «yyyy-mm-dd», «dd/mm hour:min:sec», and such. The program will save the time I got from System.currentTimeMillis() into a txt file, so even if something happens to the computer or program it needs to be able to just go right back to it’s task.
4 Answers 4
tl;dr
Serializing
java.time.Instant.now().toString()
Instant.parse( “2018-01-01T01:23:45.123456789Z” )
Formatted strings
instant.atZone( ZoneId.of( “Africa/Tunis” ) ) // Instantiate a `ZonedDateTime` object
Generate strings in other formats:
DateTimeFormatter.ofPattern( … )
DateTimeFormatter.ofLocalized…
myZonedDateTime.format( formatter )
Track Date-Time Values, Not Milliseconds
Generally speaking, tracking date-time values by millisecond-since-epoch is tricky business and should be avoided. The values are meaningless when read by humans. Different software uses different numbers (seconds versus milliseconds versus nanoseconds). Different software uses different epochs (not always the beginning of 1970 as you may be expecting). Tracking by date-time values by milliseconds like trying to track text by bits rather than using String, FileReader, and FileWriter objects. We have good date-time libraries, so use them.
Joda-Time | java.time
By good date-time libraries, I am referring to Joda-Time or the new java.time package in Java 8. Avoid the older bundled classes, java.util.Date & .Calendar, as they are notoriously troublesome.
To get started with Joda-Time, try:
System.out.println( DateTime.now() );
Then search StackOverflow for «joda» or «joda date».
ISO 8601
When serializing date-time values to text storage, use the ISO 8601 format of YYYY-MM-DDTHH-MM-SS.sss+00:00 such as 2014-03-11T23:54:15+01:00 or 2014-03-11T22:54:15Z . This format is unambiguous. The format is intuitive across various cultures. The values when sorted alphabetically are also sorted chronologically.
The Joda-Time library uses the ISO 8601 format by default. Similarly the java.time package in Java 8 (inspired by Joda-Time, defined by JSR 310) also uses ISO 8601 but extends that format by appending in brackets the proper name of the time zone such as 2014-03-11T15:54:15+08:00[America/Los_Angeles] .