-1

I know that I can create Random object and set seed for the object like this:

Random random = new Random();
random.setSeed(seed);

But what if I can't create Random object? What if I have to use Math.random()?

I know that Math.random() creates Random object behind the scene.

So the question is there any way to get the Random object created by Math.random and set seed for the object or at least get seed that the object is using?

chaika_sv
  • 384
  • 1
  • 4
  • 16

1 Answers1

-1

Math.random is just a shortcut that uses an internal Random object. If you need or want control over the seed, just don't use it, and use a (Secure)Random you create yourself. It has the same features as Math.random, plus quite a few more.

Jorn
  • 20,612
  • 18
  • 79
  • 126
  • I know it. The question is what if I can't create my own Random object? Let's say I have such a limitation. I believe I mentioned it in my initial question. – chaika_sv Jun 22 '23 at 14:40
  • Why wouldn't you be able to create it? If old code is using `Math.random`, refactor it. – Jorn Jun 22 '23 at 14:41
  • 1
    In other words, "Can I" is the wrong question. The right question is "Should I?", and the answer is "no". – Jorn Jun 22 '23 at 14:42
  • Let's say I have a code that pick a random number using Math.random() and I can't touch the code. I need to guess the number. – chaika_sv Jun 22 '23 at 14:51
  • @chaika_sv Others have already told you it can be done using reflection. I've already told you how to do it properly. What more do you want? – Jorn Jun 22 '23 at 15:02
  • Reflection doesn't work for me. Trying this https://stackoverflow.com/questions/72982904/how-to-resolve-inaccessibleobjectexception-for-field-setaccessible-in-jdk-17 – chaika_sv Jun 22 '23 at 15:08